strcat在运算符重载时无法正常工作

时间:2013-01-20 14:27:23

标签: string visual-c++ operator-overloading strcat

我正在练习运算符重载但是我无法正确执行它。谁能告诉我我在这里做错了什么。

我不明白为什么strcat没有连接两个字符串。

#include<iostream>
#include<string>

using namespace std;

class Strings
{
    char str[20];
public:
    Strings()
    {
        str[0] = '\0';
    }
    Strings(char *p)
    {
        strcpy_s(str,p);
    }

    void display()
    {
        cout<<str<<endl;
    }
    Strings operator+(Strings &);
};

Strings Strings::operator+(Strings &k)
{
    Strings temp;

    strcpy_s(temp.str,this->str);
    strcat_s(temp.str,k.str);
    return temp;

}

int main()
{
    Strings s1("Hello, "), s2("How are you?"),s3;
    s1.display();
    s2.display();
    s3.display();
    s3 = s1 + s2;
    s2.display();
}

输出结果为:

Hello,
How are you?

How are you?

2 个答案:

答案 0 :(得分:1)

您没有显示连接的字符串;改变最后一行:

s2.display();

为:

s3.display();

答案 1 :(得分:0)

当您尝试展示s3时,nulls3字符串

请再次亲自查看您的问题

    Strings s1("Hello, "), s2("How are you?"),s3;
    s1.display();    // Hello,
    s2.display();    // How are you?
    s3.display();    // '\0'
    s3 = s1 + s2;
    s2.display();    //How are you?

    s3.display();   //Add this line and test your code