Things to note about operator overloading in C++

Regarding C++ operator overloading, you can use member operator overloading or friend functions within the class. But be careful that the two cannot appear at the same time, otherwise compilation errors will occur.

#include<iostream>
using namespace std;
class Complex{
    
    
  public:
    Complex(int r=0,int i=0)
     {
    
    
      real = r;
      imag = i;
     }
   //#if 0
     Complex operator+(Complex &c) {
    
    
         cout << " internal function is called" << endl;
         Complex c2;
         c2.real = this->real + c.real;
         c2.imag = this->imag + c.imag;
         return c2;
     }
//    #endif 
     void print();
     friend Complex operator+(int a,Complex &c2); //声明友元运算符重载函数,+的左侧是整数,右侧是类的对象 
     friend Complex operator+(Complex c1,int a);//声明友元运算符重载函数,+的右侧是整数,左侧是类的对象
//     friend Complex operator+(Complex c1,Complex c2);//声明友元运算符重载函数,+的右侧是整数,左侧是类的对象 
  private:
    int real;
    int imag;
};
Complex operator+(int a,Complex &c2)  //定义友元运算符重载函数,+的左侧是整数,右侧是类的对象 
{
    
    
  Complex temp;
  cout << "friend function 1 is called" << endl;
  temp.real = a+c2.real;
  temp.imag = c2.imag;
  return temp;
}
Complex operator+(Complex c1,int a)//定义友元运算符重载函数,+的右侧是整数,左侧是类的对象 
{
    
    
  Complex temp;
  cout << "friend function 2 is called" << endl;
  temp.real = c1.real+a;
  temp.imag = c1.imag;
  return temp;
} 
#if 0
Complex operator+(Complex c1,Complex c2)
{
    
    
  Complex temp;
  cout << "friend function 3 is called" << endl;
  temp.real = c1.real+c2.real;
  temp.imag = c1.imag+c2.imag;
  return temp;
}
#endif

void Complex::print()
{
    
    
 cout<<real<<"+"<<imag<<'i'<<endl;
}

int main()
{
    
    
 Complex co1(30,40),co2(30,40),co3,co4;
 co1.print();
 
 co3=100+co1;  //co3=operator+(100,co1); 
 co3.print();
 
 co3=co2+100;  //co3=operator+(co2,100);
 co3.print();
 
 co4=co2+co3;
 co4.print();
 
 return 0;
}

Guess you like

Origin blog.csdn.net/roufoo/article/details/132635749