【发布时间】:2020-09-25 19:02:52
【问题描述】:
我有一个带有Length 类的程序。这个类有一个名为size 类型为int 的属性和一个动态的
char 类型的数组 *numb。我重载了运算符<< 和=,这样我就可以打印对象值并将一个对象的值分配给另一个对象。
如果我将operator = 的返回类型保留为void,程序似乎可以正常工作,但如果我尝试返回Length 对象,则会打印出垃圾信息。为什么?。谢谢。
这是我的代码:
class Length
{
int size;
char *numb;
public:
Length()
{
}
Length(int size, char *n);
~Length();
friend ostream & operator << (ostream &channel, const Length &l);
Length operator = (const Length &x);
};
Length::Length(int size, char *n)
{
this->size = size;
numb = new char[size];
for(int i = 0; i < size; i++)
{
numb[i] = n[i];
}
}
ostream & operator << (ostream &channel, const Length &l)
{
channel << "Size " << l.size <<endl;
for(int i = 0; i < l.size; i++)
{
channel << l.numb[i] << endl;
}
return channel;
}
Length Length::operator =(const Length &x)
{
delete [] this->numb;
this->size = x.size;
this->numb = new char[this->size];
memcpy(this->numb, x.numb, this->size);
return *this; //If I comment that line and make return type void programm works fine
}
int main()
{
char * ch = "Hello";
char * cx = "Hi";
int size = strlen(ch);
int size_x = strlen(cx);
Length h(size, ch);
Length x(size_x, cx);
cout << x; //Works fine
cout << h <<endl; //Works fine
x = h;
cout << x <<endl; //Prints junk
}
【问题讨论】:
-
阅读“三法则”,然后添加复制构造函数。 (与那个问题有点相关:
operator=应该返回一个引用,而不是一个副本) -
@Yksisarvinen 我得到了随机字符,比如数字等。但是如果我返回一个参考就可以了。
-
这并没有解决问题,但您确实不需要
std::endl所做的额外内容。使用'\n'结束一行。
标签: c++ operators overloading