C++的字符串相加问题

# include <iostream.h>class string{private: char *str;public: string(char *s=""); string operator + (string &s); void show();};
# include "string.h"string::string(char *s){str=s;}void string::show(){ cout<<str<<endl;}string string::operator + (string &s){ char *t1=new char,*t2=t1,*s1=this->str,*s2=s.str; while(*s1!='\0') { *t1=*s1;t1++;s1++; } while(*s2!='\0') { *t1=*s2;t1++;s2++; } *t1='\0'; string t(t1); return t;}void main(){ string s1("zhang"),s2("jiang"),s3; s3=s1+s2; s1.show(); s2.show(); s3.show();}

运行结果为这个,怎么回事不显示S3啊?

第1个回答  2014-10-12
看得出来,刚学C++不久,还需要了解内存空间分配,指针的概念

在做字符串连接时,需要明白再进行字符操作时,是在内存空间上操作的,没内存空间是不行的

按照你的思路
修改后代码
# include <iostream.h>
# include "string.h"

class string
{
private:
char *str;
public:
string(char *s="");
string operator + (string &s);
void show();
};

string::string(char *s)
{
str = new char[strlen(s) + 1];
strcpy(str, s);
}

void string::show()
{
cout<<str<<endl;
}

string string::operator + (string &s)
{
//计算两个字符串长度之和
int length = strlen(this->str) + strlen(s.str);
//重新分配保存字符串的空间
char *t1=new char[length + 1];

//原来this->str部分复制进新分配空间
strcpy(t1, this->str);
//尾部再连接参数s的字符串,即把s中数据复制进t1后面
strcpy(t1 + strlen(this->str), s.str);

//释放掉原来空间
//这里有点问题构造函数需要修改
delete str;
str = t1;

return t1;
}
void main()
{
string s1("zhang"),s2("jiang"),s3("");
s3=s1+s2;
s1.show();
s2.show();
s3.show();
}本回答被提问者和网友采纳
相似回答