0

I want to return integer when + 2 objects. But it caught errors

E2140 expression must have integral or unscoped enum type

Error C2110 '+': cannot add two pointers

class Sum {
    int number;
public:
    Sum(int number) : number(number) {};
    int getNumber() const { return number; }
    void setNumber(int val) { number = val; }

    int operator+ (Sum* d1) {
        int result;
        result = this->getNumber() + d1->getNumber();
        return result;
    }
};

int main() {
    Sum* num1 = new Sum(17);
    Sum* num2 = new Sum(9);

    int result = num1 + num2;
    cout << result;
}

Can I overload 2 object to get a integer result.

  • The left hand side of `Sum::operator+` must be a `Sum` object, not a `Sum*` pointer. You'd also expect the right hand side to be a `Sum` object or perhaps a `const Sum& reference` but technically it doesn't have to be. More discussion of the expected semantics of overloaded operators can be found [here](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). – Nathan Pierson Apr 23 '21 at 06:17
  • Exactly what the error message says. Overloading binary operators requires at least one of the operands to be a user-defined (e.g. a class) type. Pointers are not a user-defined type, and adding them is not allowed. Pass the argument by `const` reference, instead of as a pointer. – Peter Apr 23 '21 at 06:59

2 Answers2

0

Because the operator is defined inside the class it's left hand side must be of type Sum and the right hand side must be of type Sum* (because that's the type of parameter d1).

However, you try to add two pointers here:

int result = num1 + num2;

Correct would be to dereference the left hand side

//           V
int result = *num1 + num2;

Even better would be to overload the operator with a reference as right hand side argument and don't use new at all (You don't really need to use new in modern C++).

//             VVVVV     V
int operator+ (const Sum &d1) {
    return this->getNumber() + d1.getNumber();
}

...

int main() {
    Sum num1(17);
    Sum num2(9);

    int result = num1 + num2;
    cout << result;
}
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
-1

You are creating unnecessary pointers, why not simply:

Sum num1(17);
Sum num2(9);
int result = num1 + num2;

If you think you want to use pointers for whatever reason, you need to dereference them to add the values they point to:

Sum* num1 = new Sum(17);
Sum* num2 = new Sum(9);

int result = *num1 + *num2;
Aganju
  • 6,295
  • 1
  • 12
  • 23