简体   繁体   English

通过运算符重载的字符串连接

[英]String Concatenation through Operator overloading

QUESTION问题

Write a C++ program to overload '+' operator to concatenate two strings.编写 C++ 程序以重载“+”运算符以连接两个字符串。

This program is done on my OOP book of Robert Lafore fourth edition Object Oriented programming but seems to not be able to convert char to string.这个程序是在我的 Robert Lafore 第四版 Object 的 OOP 书中完成的。面向编程,但似乎无法将字符转换为字符串。 The program is well written and fulfills the requirement but the one error it gives makes it hard to understand.该程序编写得很好并且满足了要求,但是它给出的一个错误使它难以理解。 I cant seem to find the problem in it.我似乎无法在其中找到问题。

error it gives is that character cannot be converted to string.它给出的错误是字符无法转换为字符串。

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

Firstly, this / is not " , so the C++ compiler doesn't get that.首先,这个 / 不是" ,所以 C++ 编译器没有得到那个。

Second, a string literal is a const char[] , which decays into a const char* , so it won't call the char[] constructor.其次,字符串文字是const char[] ,它会衰减const char* ,因此它不会调用char[]构造函数。

The Fix:修复:

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

Be sure to replace your quotes with ASCII quotes ( " ).请务必将引号替换为 ASCII 引号 ( " )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM