我正在尝试熟悉 C++ 中的构造函数和析构函数。下面的程序简单地创建一个复数,在标准输入输出上打印它并退出。我创建了 3 个对象(1. 使用默认构造函数,2. 使用显式构造函数,第三个使用复制构造函数。在退出之前,它破坏了 4 个对象。为什么我下面的程序破坏的对象比构造函数创建的要多?
#include <iostream>
using namespace std;
class complex
{
private: float a; float b;
public: float real(){return a;};
float imag(){return b;};
complex(){a=0.0; b=0.0;cout << "complex no. created."<<endl;};
complex(float x, float y){a=x; b=y;};
~complex(){cout << "complex no. with real part " << this->real() << " destroyed" << endl;};
void display(){cout << a << '+' << b << 'i';}
friend ostream& operator<< (ostream & sout, complex c)
{
sout << c.a << '+' << c.b << 'i' << "\n";
return sout;
}
};
main()
{
complex c1;
complex c2(1.0,1.0);
c1.display();
cout << endl;
c2.display();
cout << endl;
cout << c2.imag() << endl;
complex c3 = c2; // this uses the default 'copy constructor'
c3.display();
cout << endl;
cout << c2;
}
我得到的输出是:
complex no. created.
0+0i
1+1i
1
1+1i
1+1i
complex no. with real part 1 destroyed
complex no. with real part 1 destroyed
complex no. with real part 1 destroyed
complex no. with real part 0 destroyed
只是为了完成,我已经在 CC 和 g++ 编译器上尝试过这个。而且他们俩的行为都是一样的。