注册 登录
编程论坛 C++教室

关于构造函数的一个问题

w378567402 发布于 2009-10-13 10:54, 402 次点击
#include<iostream>
using namespace std;
class complex{
public:
complex(){real=0;imag=0;}
complex(double i,double j){real=i;imag=j;}
complex operator + (complex &t1);
complex operator - (complex &t1);
complex operator * (complex &t1);
complex operator / (complex &t1);
void display();
private:
double real;
double imag;
};
complex complex:: operator + (complex &t1)
{complex t2;
t2.real=real+t1.real;
t2.imag=imag+t2.imag;
return t2;
}
complex complex:: operator - (complex &t1)
{complex t2;
t2.real=real-t1.real;
t2.imag=imag-t2.imag;
return t2;
}
complex complex:: operator * (complex &t1)
{complex t2;
t2.real=real*t1.real;
t2.imag=imag*t2.imag;
return t2;
}
complex complex:: operator / (complex &t1)
{complex t2;
t2.real=real/t1.real;
t2.imag=imag/t2.imag;
return t2;
}
void complex::display()
{cout<<real<<"+"<<imag<<'i'<<endl;}
int main()
{complex t1(1,2),t2(3,4),t3;
t3=t1+t2;
cout<<"t1与t2之和是:";
t3.display();
t3=t1-t2;
cout<<"t1与t2之差是:";
t3.display();
t3=t1*t2;
cout<<"t1与t2之积是:";
t3.display();
t3=t1/t2;
cout<<"t1与t2之商是:";
t3.display();
return 0;
}
为什么这个题目的构造函数一定要有第一个呢?
我是一个c++的初学者,请大家帮帮忙啊!
1 回复
#2
qq3781663962009-10-13 13:22
第一个是不带参数的构造函数,第二个带参数

下面看一个例子
 #include<iostream.h>
 
class A{
private: int a;
 
public:
    A(int x){a=x;}
    void print(){cout<<"a="<<a<<endl;}
};
 
void main(){
A q(1);}
程序写到这一步,编译没有错误,但是如果将主函数的 A q(1)  换成A q;时  就出现了错误 error C2512: 'A' : no appropriate default constructor available
1