关于构造函数的调用
//c++中构造函数不是没出现一个对象就要调用一次对应的构造函数么?那下面这个程序中,所有的对象加起来一共出现了六次,但为什么显示似乎只调用了五次?#include<iostream>
#include<cstdlib>
using namespace std;
class Complex
{
public:
Complex(int a=0,int b=0)
{
cout<<"called\n";
count++;
x=a;y=b;
}
int Getx()const
{
return x;
}
int Gety()const
{
return y;
}
void show()const
{
cout<<"x="<<x<<"\ty="<<y<<endl;
}
friend Complex operator+(Complex ,Complex);
friend Complex operator-(Complex,Complex);
friend Complex operator-(Complex);
static int count;
private:
int x;int y;
};
int Complex::count=0;
Complex operator+(Complex m,Complex n)
{
int a,b;
a=m.Getx()+n.Getx();
b=m.Gety()+n.Gety();
return Complex(a,b);
}
Complex operator-(Complex m,Complex n)
{
int a,b;
a=m.Getx()-n.Getx();
b=m.Gety()-n.Gety();
return Complex(a,b);
}
Complex operator-(Complex m)
{
int a,b;
a=-m.Getx();
b=-m.Gety();
return Complex(a,b);
}
int main()
{
Complex a(1,1),b(2,2);//调用两次构造函数
a.show();
b.show();
Complex c=a+b;//此处应该是调用调用两次构造函数
c.show();
c=a-b;//此处应该调用一次
c.show();
c=-c;//此处应该调用一次
c.show();
cout<<c.count<<endl;
}