String strcat在操作员过载情况下工作不正常
我正在练习运算符重载,但我无法正确地执行。谁能告诉我我在这里做错了什么 我不明白为什么strcat不连接两个字符串String strcat在操作员过载情况下工作不正常,string,visual-c++,operator-overloading,strcat,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) {
#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();
}
因为当您试图显示
s3
时,s3
是一个null
字符串
请你自己再看一遍你的问题
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
您没有显示连接的字符串;将最后一行更改为:
s2.display();
致:
对不起,我弄错了,我赶时间,看不清楚。谢谢大家
s2.display();
s3.display();