1. 程式人生 > >C++中的operator的兩種用法

C++中的operator的兩種用法

#include  "stdafx.h"
#include <iostream> 
#include <string> 
using  namespace   std ; 
 

/*
C++中的operator主要有兩個作用,
第一種:   操作符的過載,一是自定義物件型別的隱式轉換。 
第二種:    自定義物件型別的隱式轉換    使用格式   operator  型別()  
*/


class    A
{
public:
A( int a )
{
this->a = a; 
}


~A() {}


//-------------運算子過載------------- 
A &   operator = (const A &a)
{
cout << "過載=運算子" << endl;
this->a = a.a; 
return   *this ;
}




A    operator + ( const A &a)
{
cout << "過載+運算子" << endl; 
return   A(this->a + a.a);
}
 
 
string  operator()()
{
cout << "過載()運算子" << endl;
return   string("aaa");
}
 
int  operator()(int b)
{
cout << "過載()運算子  帶引數" << endl;
return    b;
}
 
int  operator<<(int b)
{
cout << "過載()運算子  帶引數" << endl;
return    b;
}


bool operator == (const A&a)
{
cout << "過載==運算子" << endl;
return  (this->a == a.a);
}




A* operator & () 
{
cout << "過載&運算子" << endl;
return   this;
}


char  operator [] (int i)
{
cout << "過載[]運算子" << endl;
return  i+'a' ;
}


A *  operator -> ()
{
cout << "過載->運算子" << endl; 
return  this; 
}




ostream &  operator << (ostream&  o )
{
cout << "過載<<運算子" << endl;
o << a << endl; 
return o;
}


istream &  operator >> (istream&  i)
{
cout << "過載>>運算子" << endl;
cin>> a;
return i;
}


//-------------型別轉換-------------
operator   float()
{
cout << "強制轉換為float" << endl;
return  a*0.1f;
}
 
operator const char()  
{
cout << "強制轉換為 const char" << endl;
return  'f';
}
 


operator  string()
{
cout << "強制轉換為string" << endl; 
return  string("hehe");
}


 
 
int   a; 
};




int main() {
 
A    a(11);
A    a1(0);
a1 = a;
cout << a1.a << endl;


A    a2(22);
A    a3 = a1 + a2;
cout << a3.a << endl;


  
string  a4= a1();
cout << a4 << endl;


int a5 = a2(333);
cout << a5 << endl;


cout <<( a1==a2)<< endl;


A *a6 = &a1;
cout << a6->a << endl;


char a7 = a2[4];
cout << a7 << endl;




cout << a1->a<<endl;


 
a2 >> cin;//採用友元函式更好
a2 << cout;//採用友元函式更好




//-------------------自動隱式轉換--------------------------
 
float  t1         = a1;
cout << t1 << endl;
const char  t2 = (const char) a1;
cout << t2 << endl;
string t3        = a1;
cout << t3 << endl;


}