亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

C++ 基礎(chǔ)教程

C++ 流程控制

C++ 函數(shù)

C++ 數(shù)組 & 字符串

C++ 數(shù)據(jù)結(jié)構(gòu)

C++ 類(lèi) & 對(duì)象

C++ 指針

C++ 繼承

C++ STL 教程

C++ 參考手冊(cè)

C++ 輸入輸出運(yùn)算符重載

C++ 重載運(yùn)算符和重載函數(shù)

C++ 能夠使用流提取運(yùn)算符 >> 和流插入運(yùn)算符 << 來(lái)輸入和輸出內(nèi)置的數(shù)據(jù)類(lèi)型。您可以重載流提取運(yùn)算符和流插入運(yùn)算符來(lái)操作對(duì)象等用戶(hù)自定義的數(shù)據(jù)類(lèi)型。

在這里,有一點(diǎn)很重要,我們需要把運(yùn)算符重載函數(shù)聲明為類(lèi)的友元函數(shù),這樣我們就能不用創(chuàng)建對(duì)象而直接調(diào)用函數(shù)。

下面的示例演示了如何重載提取運(yùn)算符 >> 和插入運(yùn)算符 <<。

#include <iostream>
using namespace std;
 
class Distance
{
   private:
      int feet;             // 0 到無(wú)窮
      int inches;           // 0 到 12
   public:
      // 所需的構(gòu)造函數(shù)
      Distance(){
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      friend ostream &operator<<( ostream &output, 
                                       const Distance &D )
      { 
         output << "F : " << D.feet << " I : " << D.inches;
         return output;            
      }
 
      friend istream &operator>>( istream  &input, Distance &D )
      { 
         input >> D.feet >> D.inches;
         return input;            
      }
};
int main()
{
   Distance D1(11, 10), D2(5, 11), D3;
 
   cout << "輸入對(duì)象的值 : " << endl;
   cin >> D3;
   cout << "第一次距離 : " << D1 << endl;
   cout << "第二次距離 :" << D2 << endl;
   cout << "第三次距離 :" << D3 << endl;
 
 
   return 0;
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

$./a.out
輸入對(duì)象的值 :
70
10
第一次距離 : F : 11 I : 10
第二次距離 :F : 5 I : 11
第三次距離 :F : 70 I : 10

C++ 重載運(yùn)算符和重載函數(shù)