C++ 通过运算符重载实现字符串连接

C++ 通过运算符重载实现字符串连接,c++,arrays,string,class,char,C++,Arrays,String,Class,Char,问题 < >编写一个C++程序来重载“+”运算符来连接两个字符串。 这个程序是在我的罗伯特·拉福尔第四版面向对象编程的OOP书上完成的,但似乎无法将字符转换为字符串。该程序编写得很好,满足了要求,但它给出的一个错误使其难以理解。我似乎找不到其中的问题 它给出的错误是无法将字符转换为字符串 #include <iostream> using namespace std;#include <string.h> #include <stdlib.h> clas

问题

< >编写一个C++程序来重载“+”运算符来连接两个字符串。

这个程序是在我的罗伯特·拉福尔第四版面向对象编程的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;
}
#包括
使用名称空间std#包括
#包括
类字符串//用户定义的字符串类型
{
私人:
枚举{
SZ=80
};//字符串对象的大小
char str[SZ];//保存字符串
公众:
String()//构造函数,无参数
{
strcpy(str,“”);
}
字符串(char s[])//构造函数,一个参数
{
strcpy(str,s);
}
void display()常量//显示字符串
{

CUT< P>首先,这个<代码> /<代码> 不是<代码> ,所以C++编译器没有得到。 其次,字符串文字是一个
const char[]
,它会衰减为
const char*
,因此它不会调用
char[]
构造函数

修复方法:

String(const char*s)//采用字符串文字
{
strcpy(str,s);
}

请务必用ASCII引号(
”)替换您的引号。

请注意:您的
/
双引号不是ASCII双引号
。你应该仔细检查你的文本编辑器/键盘。你目前是如何编写代码的?@alterigel是的,这是我从上面提到的教科书中复制的。这就是原因。否则,我在实现它时确实修复了它