C++操作符重载的注意事项
关于C++操作符重载,可以用类内的成员运算符重载或友元函数。但是注意两个不能同时出现,不然编译出错。
#include<iostream>
using namespace std;
class Complex{public:Complex(int r=0,int i=0){real = r;imag = i;}//#if 0Complex 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;
}
#endifvoid 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;
}