C++重載operator的示例

以下示例中定義了一個class test, 重載了<, +, +=, =, ==, <<, >>等符號:

#include<iostream>
#include<vector>
using namespace std;

class test{
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;
     }
};

int main(){
     test t0, t1(3);
     test t2(t1);
     cout << t0 << t1 << t2;
     cin >> t1;
     t2 = t1;
     t2 += t1;
     t1 += 10;
     cout << t2;
     if(t1 < t2) cout << "t1 < t2"; 
     else if(t1 == t2) cout << "t1 = t2";
     else /* t1 > t2*/ cout << "t1 > t2"; 
     cout <<endl;
     system("pause");
     return 0;
}
/******************************************************************/
對於<<和>>,用友元函數重載,如果友元函數放在類外部實現,編譯會出現錯誤:error C2593: 'operator <<' is ambiguous,而且友元函數體還不能訪問類的私有成員變量。
將友元函數的實現放在類內,就不存在上述問題;
或者以如下方式保護頭文件,也不會出現上述問題:
#include <iostream.h>
//using namespace std;

這一點很奇怪,沒找到具體原因。


發佈了39 篇原創文章 · 獲贊 1 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章