+
号可以对不同类型(int、float 等)的数据进行加法操作;<<
既是位移运算符,又可以配合 cout 向控制台输出数据。C++ 本身已经对这些运算符进行了重载。+
号实现复数的加法运算:
#include <iostream> using namespace std; class complex{ public: complex(); complex(double real, double imag); public: //声明运算符重载 complex operator+(const complex &A) const; void display() const; private: double m_real; //实部 double m_imag; //虚部 }; complex::complex(): m_real(0.0), m_imag(0.0){ } complex::complex(double real, double imag): m_real(real), m_imag(imag){ } //实现运算符重载 complex complex::operator+(const complex &A) const{ complex B; B.m_real = this->m_real + A.m_real; B.m_imag = this->m_imag + A.m_imag; return B; } void complex::display() const{ cout<<m_real<<" + "<<m_imag<<"i"<<endl; } int main(){ complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display(); return 0; }运行结果:
返回值类型 operator 运算符名称 (形参表列){
//TODO:
}
operator
是关键字,专门用于定义重载运算符的函数。我们可以将operator 运算符名称
这一部分看做函数名,对于上面的代码,函数名就是operator+
。+
,该重载只对 complex 对象有效。当执行c3 = c1 + c2;
语句时,编译器检测到+
号左边(+
号具有左结合性,所以先检测左边)是一个 complex 对象,就会调用成员函数operator+()
,也就是转换为下面的形式:
c3 = c1.operator+(c2);
c1 是要调用函数的对象,c2 是函数的实参。complex complex::operator+(const complex &A)const{ return complex(this->m_real + A.m_real, this->m_imag + A.m_imag); }return 语句中的
complex(this->m_real + A.m_real, this->m_imag + A.m_imag)
会创建一个临时对象,这个对象没有名称,是一个匿名对象。在创建临时对象过程中调用构造函数,return 语句将该临时对象作为函数返回值。
+
,实现复数的加法运算:
#include <iostream> using namespace std; class complex{ public: complex(); complex(double real, double imag); public: void display() const; //声明为友元函数 friend complex operator+(const complex &A, const complex &B); private: double m_real; double m_imag; }; complex operator+(const complex &A, const complex &B); complex::complex(): m_real(0.0), m_imag(0.0){ } complex::complex(double real, double imag): m_real(real), m_imag(imag){ } void complex::display() const{ cout<<m_real<<" + "<<m_imag<<"i"<<endl; } //在全局范围内重载+ complex operator+(const complex &A, const complex &B){ complex C; C.m_real = A.m_real + B.m_real; C.m_imag = A.m_imag + B.m_imag; return C; } int main(){ complex c1(4.3, 5.8); complex c2(2.4, 3.7); complex c3; c3 = c1 + c2; c3.display(); return 0; }运算符重载函数不是 complex 类的成员函数,但是却用到了 complex 类的 private 成员变量,所以必须在 complex 类中将该函数声明为友元函数。
c3 = c1 + c2;
语句时,编译器检测到+
号两边都是 complex 对象,就会转换为类似下面的函数调用:
c3 = operator+(c1, c2);
本文链接:http://task.lmcjl.com/news/8645.html