- #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;
- }
追问:大佬门问一下,对这段代码的解释是:当执行c3 = c1 + c2;语句时,编译器检测到+号左边(+号具有左结合性,所以先检测左边)是一个 complex 对象,就会调用成员函数operator+(),也就是转换为下面的形式:c3 = c1.operator+(c2); 我的问题:当这段代码执行到第36行:c3 = c1 + c2;后,他是怎末调用第10行:complex operator+(const complex &A) const;的函数的?一般调用函数不是用 对象.(函数名) 或者 对象->(函数名)吗,我现在的理解是当遇到重载符号+号和左侧是一个operator的对象就会调用这个重载函数,实在是云里雾里
这个代码是定义了一个复数类,通过运算符重载,用+
号实现复数的加法运算 运行的结果是:6.7 + 9.5i