C++ operator重载运算符和隐式转换功能的实现


C++ operator重载运算符和隐式转换功能的实现:

#include <iostream>
using namespace std;
class OperatorTest {
public:
    int value_;

    OperatorTest() {
        value_ = 0;
    }

    /*++A*/
    OperatorTest& operator ++() {
        value_++;
        return *this;
    }

    /*A++*/
    OperatorTest operator ++(int) {
        OperatorTest ot(*this);
        value_++;
        return ot;
    }

    /*A+B*/
    OperatorTest operator +(OperatorTest& ot) {
        OperatorTest ot_tmp;
        ot_tmp.value_ = value_ + ot.value_;

        return ot_tmp;
    }

    /*A(int)赋值*/
    OperatorTest& operator ()(int a) {
        value_ = a;
        return *this;
    }

    /*A<B*/
    bool operator <(OperatorTest& ot) {
        return value_ < ot.value_;
    }

    /*A>B*/
    bool operator >(OperatorTest& ot) {
        return value_ > ot.value_;
    }

    /*A!=B*/
    bool operator !=(OperatorTest& ot) {
        return value_ != ot.value_;
    }

    /*A==B*/
    bool operator ==(OperatorTest& ot) {
        return value_ == ot.value_;
    }

    /*A+=B*/
    OperatorTest& operator +=(OperatorTest& ot) {
        value_ += ot.value_;
        return *this;
    }

    /*A-=B*/
    OperatorTest& operator -=(OperatorTest& ot) {
        value_ -= ot.value_;
        return *this;
    }

    /*隐式转换*/
    operator int() {
        return value_;
    }
};

int main() {
    OperatorTest A, B;

    cout << "++A:" << A++ << endl;
    cout << "B++:" << ++B << endl;
    cout << "A+B:" << A + B << endl;
    cout << "A(int):" << A(3) << endl;
    cout << "A,B:" << A << "," << B << endl;
    cout << "A<B:" << (A < B) << endl;
    cout << "A>B:" << (A > B) << endl;
    cout << "A!=B:" << (A != B) << endl;
    cout << "A==B:" << (A == B) << endl;
    cout << "A+=B:" << (A += B) << endl;
    cout << "A-=B:" << (A -= B) << endl;
}

 

运算结果:

++A:0
B++:1
A+B:2
A(int):3
A,B:3,1
A<B:0
A>B:1
A!=B:1
A==B:0
A+=B:4
A-=B:3

 

可以在网上在线运行代码,C++Shell网址:http://cpp.sh/82xpny


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM