Let us say My class contain object t1. I have to add 5 along with t1. cout<<5+t1 Please post an example which satisfies the above conditions.
答案 0 :(得分:0)
Assuming you have a type MyClass
you can provide an operator+
for it and int like so:
MyClass operator+(MyClass lhs, int rhs) {
return /* ... */ ;
}
Though you want to make it commutative so add one with the reverse order as well
MyClass operator+(int lhs, MyClass rhs) {
return rhs + lhs;
}
As a complete example:
#include <iostream>
struct MyClass {
int value = 0;
};
MyClass operator+(MyClass lhs, int rhs) {
lhs.value += rhs;
return lhs;
}
MyClass operator+(int lhs, MyClass rhs) {
return rhs + lhs;
}
int main() {
MyClass mc{3};
auto result = mc + 5;
std::cout << result.value << '\n';
}
And at this point it's usually benefical to have a +=
as well. It's easy to implement +
in terms of +=
MyClass& operator+=(MyClass& lhs, int rhs) {
lhs.value += rhs;
return lhs;
}
MyClass operator+(MyClass lhs, int rhs) {
lhs += rhs;
return lhs;
}
MyClass operator+(int lhs, MyClass rhs) {
return rhs + lhs;
}