我有一个程序,使用+运算符重载添加两个复数。该程序是:为什么我在明确写入Copy构造函数后得到垃圾值?
#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;
之后发生的事情是执行?”
其他人已经回答了你的版本不起作用的原因。我会补充说,没有它的原因是编译器会尝试默认生成一个,如果你不这样做的话。而在这个特定的情况下,默认的就好了。 –
另外,你为什么要用'c3 = c1.operator +(c2);'?来添加复数。是不是重载'+'操作符能够写入'c1 + c2'的重点? :) – Eutherpy