C++中的operator的两种用法

#include  "stdafx.h"
#include  
#include  
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<

 
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;


}

你可能感兴趣的:(windows,C/C++)