Can we add "User defined Datatype" + "Predefined Data Type" Using Operator Overloading in c++

时间:2019-04-16 22:31:44

标签: c++

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.

1 个答案:

答案 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;
}