C++運算子多載簡單練習 寫一個Integer封裝類

來源:互聯網
上載者:User

標籤:

// Operator.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <iostream>#include <string>using namespace  std;class Integer{public: //explicit如果添加explicit就不能進行隱式構造//隱式構造不會導致拷貝建構函式調用Integer(int num):m_num(num){}//覆蓋了拷貝建構函式就必須對拷貝對象的成員進行值賦值 有必要的時候還要進行深層拷貝比如重新分配記憶體Integer(const Integer&integer){   m_num=integer.m_num;    cout<<"CPY CONSTRUCTION FUNCTION CALLED"<<endl;}//尾碼形式//如果尾碼形式那麼形參會是0void operator++(int i){   this->m_num=m_num+1;}//首碼形式void operator++(){this->m_num++;}//前置--void operator--(){this->m_num--;}//尾碼形式void operator--(int i){this->m_num=m_num-1;}//重載+ 如果接受的不是  Integer&integerRef那麼依然會觸發拷貝建構函式Integer operator+(Integer &integerRef){return Integer(m_num+integerRef.m_num);}Integer operator+(int i){ return m_num+i;}Integer operator-(int i){return m_num-i;}//重載=void operator=(int i){m_num=i;}//重載+= -=void operator+=(int i){          m_num+=i;}void operator-=(int i){m_num-=i;}//傳回值int  ToVal(){return m_num;}//函數返回  賦值會導致拷貝構造調用Integer GetObj(){return *this;}//轉換成字串 const string ToString(){   char buf[10]="";        _itoa_s(m_num,buf,10);return string(buf) ;}//COPY MYSELF//只有返回新的對象 或者建立新的對象通過其他對象初始化的時候 才會觸發拷貝構造  或者函數體內部建立一個對象並且把對象作為傳回值 才會觸發 拷貝建構函式調用//如果return  Integer(m_num);是不會觸發拷貝構造的//仿函數Integer operator()(){       return *this;}//重載  對於ios流類庫的 標準輸入 標準輸出 標準錯誤輸出  所以我們只能聲明<< >>插入提取運算子為 友元函數friend istream& operator >>(istream&is,Integer&intObj);friend ostream& operator <<(ostream&os,Integer&intObj);//從對象提取資料到變數 << >>運算子多載void operator>>(int &i){i=m_num;}//輸出到對象 void operator<<(int i){m_num=i;}private:int m_num;protected:};//重載IO istream& operator >>(istream&is,Integer&intObj){    is>>intObj.m_num; return is;}ostream& operator <<(ostream&os,Integer&intObj){os<<intObj.m_num ;return os;}int _tmain(int argc, _TCHAR* argv[]){   //implicitInteger integerObj1=1;Integer integerObj2=2;//integerObj1=integerObj2; 不會觸發拷貝建構函式  Integer obj=integerObj1 才會觸發拷貝構造調用//相當於integerObj++0integerObj1++;//相當於++x++integerObj1; cout<<"integerObj1="<<integerObj1.ToVal()<<endl;Integer intObjCmb=integerObj1+integerObj2;cout<<"intObjCmb="<<intObjCmb.ToVal()<<endl;Integer w=integerObj1;cout<<"w="<<w.ToString()<<endl;w+=2 ;cout<<"w+2="<<w.ToString()<<endl;cout<<"Copy W="<<w().ToString()<<endl;//重載標準輸入和輸出.....w=125;cout<<"W="<<w<<endl;int i;w>>i ;cout<<"i=w="<<w<<endl ;w<<1000;cout<<"w="<<w<<endl ;w>>i ;cout<<"i=w="<<w<<endl ;return 0;}

C++運算子多載簡單練習 寫一個Integer封裝類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.