c++之operator运算符重载

时间:2022-04-23 22:20:30

转载:http://blog.chinaunix.net/uid-21411227-id-1826759.html

一、实例

1.用成员函数来重载“+”运算符

vi test.cpp

#include <iostream>
using namespace std;
class X{
   int i;
public:
   X(int ii=0){i=ii;}
   X operator   +(const X &rx){
       i+=rx.i;
       return X(i);
   }
   int GetI(){return i;}
};
int main(){
   X a(1),b(3);
   cout<<(a+b).GetI()<<endl;
   return 0;
}
g++ -o test test.cpp

./test

4
2.用类的友元函数来重载“+”运算符

vi test.cpp

#include <iostream>
using namespace std;
class Complex{
public:
   Complex(double r=0.0,double i=0.0){
       real=r;
       image=i;
   }
   friend Complex operator+(const Complex&,const Complex&);
   void display();
private:
   double real;
   double image;
};

Complex operator+(const Complex &c1,const Complex &c2){
   return Complex(c1.real+c2.real,c1.image+c2.image);
}

void Complex::display(){
   cout<<"("<<real<<","<<image<<"i)"<<endl;
}

int main(){
   Complex c1(3,4),c2(5,-10),c3;
   c3=c1+c2;
   cout<<"c1=";c1.display();
   cout<<"c2=";c2.display();
   cout<<"c1+c2=";c3.display();
   return 0;
}
g++ -o test test.cpp

./test

c1=(3,4i)
c2=(5,-10i)
c1+c2=(8,-6i)