2
struct Test {
    int A = 0;
    int B = 0;
};

Test* operator+(const Test *x, const Test *r) {

    Test *test = new Test;
    test->A = x->A + r->A;
    test->B = x->B + r->B;
    return test;
}

Why this wont work and give's :

3 IntelliSense: nonmember operator requires a parameter with class or enum type

4
  • 1
    The message should be pretty clear, you can't use pointers. Also, doing this will give you memory leaks. Who will free the memory returned by the function? Commented Jan 8, 2016 at 20:22
  • Test x, r; Test *test = (&x + &r); delete test; Commented Jan 8, 2016 at 20:27
  • 3
    @user3550045 Don't overuse pointers, especially raw pointers. Pointers were designed with a very specific point in mind, not for Java-like syntax in C++. Commented Jan 8, 2016 at 20:30
  • And when you have multiple additions in a row, like e.g. a + b + c? Or if you want to use addition as part of another expression, e.g. as argument to a function call? You're going to split it up into multiple statements and temporary variables too? Lot of work for something that should be simple. Commented Jan 8, 2016 at 20:32

1 Answer 1

6

Apparently, the operator+ request that the first argument not be a pointer. This would work:

Test* operator+(const Test &x, const Test& r){

    Test *test = new Test;
    test->A = x.A + r.A;
    test->B = x.B + r.B;
    return test;
}

But it's safer if you don't return a pointer, like Jonachim said. You should do this:

Test operator+(const Test &x, const Test& r){

    Test test;
    test.A = x.A + r.A;
    test.B = x.B + r.B;
    return test;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thats work - > Test* operator+(const Test & x, const Test *r)
Good answer, I'd change You could do this to You should do this.
as you said it's looks you can't use the first argument as pointer wired !,, anyway thank's for the clarifying.
@user3550045, it is not weird. C++ clearly specifies that you can't overload operators for built-in types.
The first argument can be a pointer. All that's required is that at least one of the arguments is a user-defined type. That can be the first argument, or the second, or both.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.