0

演算子のオーバーロードを練習していますが、正しく実行できません。私がここで何をしているのか誰にでも教えてもらえますか。

2 つの文字列を連結しない理由がわかりません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 に答える