【问题标题】:String Concatenation through Operator overloading通过运算符重载的字符串连接
【发布时间】:2021-07-29 07:35:12
【问题描述】:

问题

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

这个程序是在我的 Robert Lafore 第四版面向对象编程的 OOP 书中完成的,但似乎无法将 char 转换为字符串。该程序编写得很好并且满足了要求,但是它给出的一个错误使它难以理解。我似乎找不到其中的问题。

它给出的错误是字符无法转换为字符串。

#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;
}

【问题讨论】:

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

标签: c++ arrays string class char


【解决方案1】:

首先,这个/ 不是",所以C++ 编译器没有得到那个。

其次,字符串文字是const char[]衰减const char*,因此它不会调用char[]构造函数。

修复:

String(const char* s) //takes a string literal
{
    strcpy(str, s);
}

请务必将引号替换为 ASCII 引号 (")。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2014-02-27
    相关资源
    最近更新 更多