我有一个程序使用 + 运算符重载将两个复数相加。程序是:
#include<iostream>
class Complex
{
int a, b;
public:
Complex()
{
std::cout<<"\n Normal constructor ";
}
void setData(int x, int y)
{
a = x; b = y;
}
void showData()
{
std::cout<<"a = "<<a<<std::endl<<"b = "<<b<<std::endl;
}
Complex operator + (Complex c)
{
Complex temp;
temp.a = a + c.a;
temp.b = b + c.b;
return temp;
}
Complex(Complex &z)
{
std::cout<<"\n The copy constructor is called ";
}
};
int main()
{
Complex c1, c2, c3;
c1.setData(2, 3);
c2.setData(4, 5);
c3 = c1+c2;
c3.showData();
return 0;
}
在这里,当我没有显式编写复制构造函数时,该程序会给出正确的输出。但是在编写复制构造函数后输出的是垃圾值,我想知道为什么程序会产生垃圾值?
输出实例:
Normal constructor
Normal constructor
Normal constructor
The copy constructor is called
Normal constructor a = -1270468398
b = 32769
请说“c3 = c1+2;
执行后发生了什么?”
最佳答案
您忘记在复制构造函数中复制成员。如果您自己编写,则必须这样做。由于您没有对成员进行默认初始化,在 int
的情况下,这意味着没有初始化发生,因此您有一个垃圾值。
你的拷贝构造函数应该是
Complex(const Complex &z) : a(z.a), b(z.b)
{
std::cout<<"\n The copy constructor is called ";
}
您还应该通过const&
接收要复制的对象,以便您可以复制临时对象。 Complex(Complex &z)
无法做到这一点。
关于c++ - 为什么我在显式编写复制构造函数后得到垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35509918/