首页 > 代码库 > C++ 运算符的重载

C++ 运算符的重载

#include <iostream>#include <stdio.h>using namespace std;class Complex //复数类{public:double real;//实数double imag;//虚数Complex(double real=0,double imag=0){  this->real=real;  this->imag=imag;}};Complex operator+(Complex com1,Complex com2)//运算符重载函数{return Complex(com1.real+com2.real,com1.imag+com2.imag);}int main(){    Complex com1(10,10),com2(20,20),sum;    sum=com1+com2;//或sum=operator+(com1,com2)    cout<<"sum的实数部分为"<<sum.real<<endl;    cout<<"sum的虚数部分为"<<sum.imag<<"i"<<endl;    getchar();    return EXIT_SUCCESS;}