# sdau -- 运算符重载（1），，。

Sizeof 不要当作普通的运算符

=,/=,%=,&=,|=,^=,<<=,>>=;

C++中不能用友元函数重载的运算符有 = （） ［］ ->

``````例 复数运算

#include<iostream>
using namespace std;
class Complex
{  public:

Complex( double r =0, double i =0 ) {  Real = r ; Imag = i ; }
Complex(int a) {  Real = a ; Imag = 0 ; }

void print() const ;
friend Complex operator+(const Complex &c1, const Complex &c2 ) ;
friend Complex operator-(const Complex &c1, const Complex &c2 ) ;
friend Complex operator- ( const Complex & c ) ;         //前置一元运算符重载

private:
double Real, Imag ; };例 复数运算
Complex operator + ( const Complex & c1, const Complex & c2 )
{
double r = c1.Real + c2.Real ; double i = c1.Imag+c2.Imag ;
return Complex ( r, i ) ;
}

Complex operator - ( const Complex & c1, const Complex & c2 )
{
double r = c1.Real - c2.Real ; double i = c1.Imag - c2.Imag ;
return Complex ( r, i ) ;
}

Complex operator- ( const Complex & c )
{  return Complex ( -c.Real, - c.Imag ) ; }

void Complex :: print() const
{  cout << '(' << Real << " , " << Imag << ')' << endl ; }
//构造返回对象

int main()
{  Complex c1( 2.5,3.7 ), c2( 4.2, 6.5 ) ;
Complex c ;
c = c1 - c2 ; // operator-(c1,c2)
c.print() ;
c = 25 + c2 ;// operator+(25,c2)
c.print() ;
c = c2 + 25 ;// operator+(c2,52)
c.print() ;
c = - c1 ; // operator-(c1)
c.print() ; }
``````

``````成员函数重载++

#include<iostream>
using namespace std;
class Increase
{  public :
Increase ( ) {  value=0; }
void display( ) const {  cout<<value<<'\n'; } ;
Increase operator ++ ( ) ; // 前置
Increase operator ++ ( int ) ; // 后置
private: unsigned value ;
};
Increase Increase :: operator ++ ( )
{  value ++ ; return *this ; }
Increase Increase :: operator ++ ( int )
{  Increase temp; temp.value = value ++ ; return temp; }
int main( )
{  Increase a , b , n ; int i ;
for ( i = 0 ; i < 10 ; i ++ ) a = n ++ ;
cout <<"n= " ; n.display( ) ; cout <<"a= " ;
a.display( ) ;
for ( i = 0 ; i < 10 ; i ++ ) b = ++ n ;
cout << "n= " ; n.display( ) ; cout << "b= " ;
b.display( ) ;
}
``````
``````友元函数重载++

#include<iostream>
using namespace std;
class Increase
{  public :
Increase ( ) {  value=0; }
void display( ) const {  cout<<value<<'\n'; } ;
friend Increase operator ++ ( Increase & ) ; // 前置
friend Increase operator ++ ( Increase &, int ) ; // 后置
private: unsigned value ;
};
Increase operator ++ ( Increase & a )
{  a.value ++ ; return a ; }
Increase operator ++ ( Increase & a, int )
{  Increase temp(a); a.value ++ ; return temp; }int main( )
{  Increase a , b , n ; int i ;
for ( i = 0 ; i < 10 ; i ++ ) a = n ++ ;
cout <<"n= " ; n.display( ) ; cout <<"a= " ;
a.display( ) ;
for ( i = 0 ; i < 10 ; i ++ ) b = ++ n ;
cout << "n= " ; n.display( ) ; cout << "b= " ;
b.display( ) ;
}
``````

原文作者：Another_hacker
原文地址: https://blog.csdn.net/Another_hacker/article/details/106295229
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。