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
Make Change - Focus on Computer Vision and Pattern Recognition
版权声明:本文为博主原创文章,未经博主允许不得转载
版权声明:本文为博主原创文章,未经博主允许不得转载