C++中運算符重載

下面代碼實現+、()、=的運算符重載,僅供參考。

#include <iostream>

class Body{
public:
    Body(int a = 0):m_a(a) {}
    ~Body() {}

#include <iostream>

class Body{
public:
    Body(int a = 0):m_a(a) {}
    ~Body() {}

    Body(const Body& a) {
        this -> m_a = a.m_a;
    }
    // +運算符重載
    Body operator+(const Body& a) {
        Body bd;
        bd.m_a = this -> m_a + a.m_a;
        return bd;
    }
    // ()運算符重載
    int operator()(int i) {
        return this -> m_a + i;
    }
    // =運算符重載
    Body& operator=(const Body& a) {
        this -> m_a = a.m_a;
        return *this;
    }

    int get() {
        return m_a;
    }

private:
    int m_a;
};


int main(int argc, char** args) {
    Body a(1);
    Body b(100);
    Body result = a = b;
    std::cout << "a: " << result.get() << std::endl;
    std::cout << (a + b).get() << std::endl;
    std::cout << a(999) << std::endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章