如何解决通过运算符重载的字符串连接
问题
编写一个 C++ 程序来重载“+”运算符以连接两个字符串。
这个程序是在我的 Robert Lafore 第四版面向对象编程的 OOP 书中完成的,但似乎无法将字符转换为字符串。该程序编写得很好并且满足要求,但是它给出的一个错误使其难以理解。我似乎无法找到其中的问题。
它给出的错误是字符无法转换为字符串。
#include <iostream>
using namespace std;#include <string.h>
#include <stdlib.h>
class String //user-defined string type
{
private:
enum {
SZ = 80
}; //size of String objects
char str[SZ]; //holds a string
public:
String() //constructor,no args
{
strcpy(str,"");
}
String(char s[]) //constructor,one arg
{
strcpy(str,s);
}
void display() const //display the String
{
cout << str;
}
String operator + (String ss) const //add Strings
{
String temp;
if (strlen(str) + strlen(ss.str) < SZ) {
strcpy(temp.str,str); //copy this string to temp
strcat(temp.str,ss.str); //add the argument string
} else {
cout << “\nString overflow”;
exit(1);
}
return temp; //return temp String
}
};
////////////////////////////////MAIN////////////////////////////////
int main() {
String s1 = “\nMerry Christmas!“; //uses constructor 2
String s2 = “Happy new year!”; //uses constructor 2
String s3; //uses constructor 1
s1.display(); //display strings
s2.display();
s3.display();
s3 = s1 + s2; //add s2 to s1,//assign to s3
s3.display();
cout << endl;
return 0;
}
解决方法
首先,这个 “
/”
不是 "
,所以 C++ 编译器没有得到它。
其次,字符串文字是一个 const char[]
,它衰减成一个 const char*
,所以它不会调用 char[]
构造函数。
修复:
String(const char* s) //takes a string literal
{
strcpy(str,s);
}
请务必将您的引号替换为 ASCII 引号 ("
)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。