C++有時它的確是個耐玩的東東。operator它有兩種用法,一種是operator overloading(操做符重載),一種是operator casting(操做隱式轉換)。
1.operator overloading
C++能夠經過operator 重載操做符,格式以下:類型T operator 操做符 (),如比重載+,以下所示
template<typename T> class A
{
public:
const T operator + (const T& rhs)
{
return this->m_ + rhs;
}
private:
T m_;
};
又好比STL中的函數對象,重載(),這是C++中較推薦的寫法,功能與函數指針相似,以下所示
template<typename T> struct A
{
T operator()(const T& lhs, const T& rhs){ return lhs-rhs;}
};
2 operator casting
C++能夠經過operator 重載隱式轉換,格式以下: operator 類型T (),以下所示
class A
{
public:
operator B* () { return this->b_;}
operator const B* () const {return this->b_;}
operator B& () { return *this->b_;}
operator const B& () const {return *this->b_;}
private:
B* b_;
};
A a;
當if(a),編譯時,其中它轉換成if(a.operator B*()),其實也就是判斷 if(a.b_)
============================================================= 函數
class test{ this
public:
int v;
/*構造函數*/
test():v(0){}
test(const int &a):v(a){}
test(const test &t1):v(t1.v){}
/*如下重載小於號 < */
//比較兩個對象的大小
bool operator<(const test &t1) const{
return (v < t1.v);
}
//比較對象和int的大小
bool operator<(const int &t1) const{
return (v < t1);
}
//友元函數,比較int和對象的大小
friend inline bool operator<(const int &a, const test & t1){
return (a < t1.v);
}
/*如下重載賦值號 = */
//對象間賦值
test & operator=(const test &t1){
v = t1.v;
return *this;
}
//int賦值給對象
test & operator=(const int &t1){
v = t1;
return *this;
}
/*如下重載加號 + */
//對象加上 int
test operator+(const int & a){
test t1;
t1.v = v + a;
return t1;
}
//對象加對象
test operator+(test &t1){
test t2;
t2.v = v + t1.v;
return t2;
}
/*如下重載加等號 += */
//對象加上對象
test &operator+=(const test &t1){
v += t1.v;
return *this;
}
//對象加上int
test &operator+=(const int &a){
v += a;
return *this;
}
/*如下重載雙等號 == */
//對象==對象
bool operator==(const test &t1)const{
return (v == t1.v);
}
//對象==int
bool operator==(const int &t1)const{
return (v == t1);
}
/*如下重載 輸入>> 輸出<< */
/*友元函數,輸出對象*/
friend inline ostream & operator << (ostream & os, test &t1){
cout << "class t(" << t1.v << ")" << endl;
return os;
}
/*友元函數,輸入對象*/
friend inline istream & operator >> (istream & is, test &t1){
cin >> t1.v;
return is;
}
};