|
- #include <iostream>
- using namespace std;
- class Complex{
- public:
- double x,y;
- Complex(double _x=0.0,double _y=0.0):x(_x),y(_y){}
- Complex(const Complex&rhs){
- cout<<"Complex(const Complex&) called "<<endl;
- x=rhs.x;
- y=rhs.y;
- }
- Complex& operator=(const Complex& rhs){
- cout<<"operator=(const Complex&) called "<<endl;
- if(this==&rhs)return *this;
- x=rhs.x;
- y=rhs.y;
- return *this;
- }
- void print(){
- std::cout<<x<<"+"<<y<<"i"<<std::endl;
- }
- ~Complex(){
- std::cout<<"destructing..."<<std::endl;
- }
- };
- Complex operator+(const Complex&a,const Complex&b){
- Complex result(a.x+b.x,a.y+b.y);
- result.print();
- return result;
- }
- int main(){
- Complex a(3,6);
- Complex b(5,63.4);
- a.print();
- b.print();
- Complex c=a+b;//情况二:如果把这句分为两句:Complex c; c=a+b;
- c.print();
- return 0;
- }
复制代码 Complex c=a+b;时 operator= 不会被调用
Complex c; c=a+b; 则operator= 会被调用
什么原因。。。。
 |
|