0

我正在练习运算符重载,但我无法正确完成。谁能告诉我我在这里做错了什么。

我不明白为什么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?
4

2 回答 2

1

You aren't displaying the concatenated string; change the last line from:

s2.display();

to:

s3.display();
于 2013-01-20T14:31:39.260 回答
0

Because s3 is a null string when you are trying to disply s3

Please look at your question yourself once again

    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
于 2013-01-20T14:30:45.363 回答