构造函数和运算符重载的理解

2018-10-14  本文已影响17人  努力护肤的程序媛
'''
 #include <iostream>

using namespace std;

class Complex{
int real;
int image;
public:
Complex(){
    cout<<"default constructor is called"<<endl;
}
Complex(int r, int i=0){
    real = r;
    image = i;
    cout<<"constructor is called"<<endl;
}

~Complex(){
    cout<<"deconstructor is called"<<endl;
}

friend Complex operator+(const Complex &a, const Complex &b){
    return Complex(a.real + b.real, a.image + b.image);
}

friend ostream &operator<<(ostream &o, const Complex &a){
    o<<a.real<<"+"<<a.image<<"i";
}
 };
int main() {

Complex a(5,6);
cout<<a+7<<endl;
cout<<"---------------------------------------"<<endl;
cout<<8+a<<endl;
return 0;
  }
'''

以上述代码为例子,当需要对运算符“+”进行重载的时候,如果将重载函数写成类的成员函数,将只能实现a+7,而不能实现8+a。或者说,可以写两个全局重载函数:

'''
Complex(int n,  const Complex &a){
  return Complex(a.real + n, a.imag);
}
 Complex(const Complex &a, int n){
  return Complex(a.real + n, a.imag);
}
''' 

但是这两个函数可以简化写成一个函数:

  '''
  Complex operator+(const Complex &a, const Complex &b){
      return Complex(a.real + b.real, a.image + b.image);
  }
  '''

这样a+8 或者 7+a在运行的时候,首先会调用构造函数将8或7表示成一个临时的Complex对象,然后再调用运算符重载函数。

上一篇 下一篇

猜你喜欢

热点阅读