Overloaded operators

Can someone explain to me why the codes below give an error? Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
Given the following code:
#include <iostream>

const int & operator+(const int & lhs, 
                const int & rhs) {
   return lhs+rhs;
}

int main(void) {
  std::cout << 5+7;
  return 0;
}
What is the result of compilation?   Success ✘   Undefined    Error ✔   Warning
"an error"
It would have been nice of you to post that error too. Then we could help you to learn to read the words of your compiler.

4:32: error: 'const int& operator+(const int&, const int&)' must have an argument of class or enumerated type

The language defines both type int and operator+ that takes int's.
You don't need to define + for ints.
You are not alloved to redefine + for ints.

You can define + for custom types.
You cannot change the meaning of operators for built-in types. When overloading operators at least one of the types need to be a class or enum type.
Topic archived. No new replies allowed.