纠错程序C++

来源:百度知道 编辑:UC知道 时间:2024/05/06 02:38:02
上次发了一个但是代码不全,这次发个齐全的。其中有两个函数有问题,都是关于函数重载,一个是operator+,一个是operator=,代码如下:
.h文件:
#include<iostream.h>
class astring1
{
private:
int length;
char*contents;
public:
void set_contents(char*in_contents);
void print();
astring1 operator+(astring1 &obj1);
void operator=(astring1 &obj1);

};
void astring1::set_contents(char*in_contents)
{
contents=in_contents;
int len=0;
while(*in_contents++!='\0')
len++;
length=len;
}
void astring1::print()
{
cout<<"The string is: "<<contents<<endl<<"the length is: "<<length<<endl;
}
astring1 astring1::operator+(astring1 &obj1)
{
astring1 temp;
temp.length=length+obj1.length;
temp.contents=contents;
while(*contents!='\0')
*contents++;
while(obj1.contents!='\0')

private:
int length;
char*contents; // !!!

所以
aa.set_contents("hello!");
bb.set_contents("hello!");
两个hello都是temp量, 这两句一过就不存在了, 你比较内存中的垃圾有可能会相同吗??

看来你的string1中真的没有做深拷贝?