#include<iostream> using namespace std; class complex{ public: complex(const complex &a); //拷贝构造函数 void set(int,int); void print(); complex operator+ (complex &a); complex operator- (complex &a); complex operator* (complex &a); complex operator/ (complex &a); private: int real,image; }; complex::complex(const complex &a){ //拷贝构造函数 real=a.real; image=a.image; } void complex::set(int x, int y){ real=x; image=y; } void complex::print(){ if(image>=0) cout<<real<<"+"<<image<<"i"<<endl; else if(image<0) cout<<real<<image<<"i"<<endl; } complex complex::operator+ (complex &a){ complex b; b.real=real+a.real; b.image=image+a.image; return b; } complex complex::operator- (complex &a){ complex b; b.real=real-a.real; b.image=image-a.image; return b; } complex complex::operator* (complex &a){ complex b; b.real=real*a.real-image*a.image; b.image=image*a.real+image*a.image; return b; } complex complex::operator/ (complex &a){ complex b; b.real=(real*a.real+image*a.image)/(a.real*a.real+a.image*a.image); b.image=(image*a.real-image*a.image)/(a.real*a.real+a.image*a.image); return b; } int main(){ complex a,c; a.set(1,2); complex b=a; c=a+b; c.print(); }
解决方案
40
假如你为类写好了拷贝构造函数的话,那么默认的拷贝构造函数将不再起作用。
所以你相似的定义变量complex b;都会报错。
所以需要加上一个默认构造函数
所以你相似的定义变量complex b;都会报错。
所以需要加上一个默认构造函数
#include<iostream> using namespace std; class complex{ public: complex(){} complex(const complex &a); //拷贝构造函数 void set(int,int); void print(); complex operator+ (complex &a); complex operator- (complex &a); complex operator* (complex &a); complex operator/ (complex &a); private: int real,image; }; complex::complex(const complex &a){ //拷贝构造函数 real=a.real; image=a.image; } void complex::set(int x, int y){ real=x; image=y; } void complex::print(){ if(image>=0) cout<<real<<"+"<<image<<"i"<<endl; else if(image<0) cout<<real<<image<<"i"<<endl; } complex complex::operator+ (complex &a){ complex b; b.real=real+a.real; b.image=image+a.image; return b; } complex complex::operator- (complex &a){ complex b; b.real=real-a.real; b.image=image-a.image; return b; } complex complex::operator* (complex &a){ complex b; b.real=real*a.real-image*a.image; b.image=image*a.real+image*a.image; return b; } complex complex::operator/ (complex &a){ complex b; b.real=(real*a.real+image*a.image)/(a.real*a.real+a.image*a.image); b.image=(image*a.real-image*a.image)/(a.real*a.real+a.image*a.image); return b; } int main(){ complex a,c; a.set(1,2); complex b=a; c=a+b; c.print(); }