c++ 操作符重載

來源:互聯網
上載者:User

c++ 操作符重載

 

 

 /* file = main.cpp 涉及操作符重載,友元函數,重載類型轉換*/
#include <iostream>
#include "testClass.h"
using namespace std;

int main()
{
    testClass tc1(2);
    testClass tc2(3);
    testClass tc3 = 1 + tc1 + tc2 + 4;// 重載加法
    testClass tc4 = 5 - tc2 - tc1 - 1;// 重載減法
    int a = tc1;// 重載了類型轉換
    cout << "tc3:= " << tc3 << ", tc4:=" << tc4 << endl;
    // 重載了類型轉換才能用下面這樣的語句
    cout << "tc3 + t4 := " << tc3 + tc4 << endl;
    cout << "tc3 - t4 := " << tc3 - tc4 << endl;
    return 0;
}
/* file = testClass.h */
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <iostream>
class testClass
{
    public:
        testClass(int i);
        virtual ~testClass();
        testClass operator +(testClass & sf) const;
        testClass operator +(int j) const;
        testClass operator -(testClass & sf) const;
        testClass operator -(int j) const;
        operator int() const;// 重載類型轉換;必須是成員函數,零參數,無傳回值
        friend testClass operator +(int j, testClass & sf);
        friend testClass operator -(int j, testClass & sf);
        friend std::ostream & operator <<(std::ostream & os, testClass & sf);
    protected:
    private:
        int m_i;
};

#endif // TESTCLASS_H

/* file = testClass.cpp */
#include "testClass.h"

testClass::testClass(int i)
{
    this->m_i = i;
}

testClass::~testClass()
{
}

testClass testClass::operator +(testClass & sf) const{
testClass tc(this->m_i + sf.m_i);
return tc;
}

testClass testClass::operator +(int j) const{
testClass tc(this->m_i + j);
return tc;
}

testClass operator +(int j, testClass & sf){
   return sf + j;
}

testClass testClass::operator -(testClass & sf) const{
testClass tc(this->m_i - sf.m_i);
return tc;
}

testClass testClass::operator -(int j) const{
testClass tc(this->m_i - j);
return tc;
}

testClass operator -(int j, testClass & sf){
testClass tc(j - sf.m_i);
return tc;
}

testClass::operator int() const{
return this->m_i;
}

std::ostream & operator <<(std::ostream & os, testClass & sf){
    os << sf.m_i;
    return os;
}
共含三個檔案,在winxp + codeblock 8.02 上測試通過,由於codeblock 新建立的類檔案標頭檔放在include路徑下,需要在project -> build options -> Search directories -> Compiler -> Add , 添加一個include 路徑,否則codeblock 會報告找不到標頭檔"testClass.h"

 

 

 

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.