C++ operator overloading with pointers
11,105
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;
}
Author by
Saef Myth
Updated on November 29, 2022Comments
-
Saef Myth over 1 year
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
-
Some programmer dude over 8 yearsThe 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?
-
Saef Myth over 8 yearsTest x, r; Test *test = (&x + &r); delete test;
-
vsoftco over 8 years@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++.
-
Some programmer dude over 8 yearsAnd 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.
-
-
Saef Myth over 8 yearsThats work - > Test* operator+(const Test & x, const Test *r)
-
vsoftco over 8 yearsGood answer, I'd change You could do this to You should do this.
-
Saef Myth over 8 yearsas you said it's looks you can't use the first argument as pointer wired !,, anyway thank's for the clarifying.
-
SergeyA over 8 years@user3550045, it is not weird. C++ clearly specifies that you can't overload operators for built-in types.
-
Benjamin Lindley over 8 yearsThe 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.