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

时间:2021-09-18 01:07:36

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

#include <iostream>
using namespace std;
class OperatorTest {
public:
int value_; OperatorTest() {
value_ = ;
} /*++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() << 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:
B++:
A+B:
A(int):
A,B:,
A<B:
A>B:
A!=B:
A==B:
A+=B:
A-=B:

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