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

'''
 #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对象,然后再调用运算符重载函数。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,221评论 0 13
  • C++运算符重载-上篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 2,329评论 0 51
  • C++语言的一个很有意思的特性就是除了支持函数重载外还支持运算符重载,原因就是在C++看来运算符也算是一种函数。比...
    欧阳大哥2013阅读 2,723评论 0 8
  • 有时候,我在想,真不知道自己能做什么。特别是为你做什么。在你身边。感觉自己像个孩子一样手足无措。无法猜测你的心。不...
    _苏陌年阅读 677评论 0 0
  • 上周六,眼神科技创始人周军做客【关键一课】第三期,带来主题分享——“生物识别技术的应用未来”,大咖说为您整理如下。...
    大咖说阅读 287评论 0 0