View Full Version : Operator overloading C++
I've got an overloaded operator +
newtype X, Y, Z, W;
W = X + Y; // works fine
W = Y + X; // works fine
// but with more arguments I'm getting compiler error
// saying there is no match for operator+
W = X + Y + Z;
Sample code
newtype operator+(newtype &A, newtype &B)
{
newtype C;
//more code
return C;
}
Is there something missing?
Just eyeballing it, I agree with the compiler.
Temporary objects cannot be implicitly converted to modifiable references -- the standard doesn't allow it, and even if it did, you shouldn't do it anyways because it can lead to all sorts of really, really hard to debug problems.
Since X+Y is a temporary value, it cannot be converted into the modifiable reference required by your operator+.
Now, the fix is actually very easy: write operator+ correctly! The arguments almost certainly should not be modifiable references -- they should be const references.
(Well, technically there are occasions where you're better off without using references at all)
CFDFEAGURU
Sep12-09, 03:38 PM
Not sure what you are doing but my code compilies fine. I am using 2008 C++ Express edition.
Here is my code.
#include<cmath>
#include<iomanip>
#include<iostream>
int x,y,z,w,pause; // needed variables
using namespace std;
int main()
{
x = 1;
y = 2;
z = 3;
w = x+y;
w = y+x;
w = x+y+z;
cout << w << endl;
cin >> pause; // dummy input to keep the output screen visible
return 0;
}
Thanks
Matt
Even if "your code compiles fine" does not mean it is right. Besides, per your first post, your code does not compile fine. It doesn't even compile, period. I would not call that "fine".
Make the arguments to newtype operator+ be const references and then it will be fine.
CFDFEAGURU
Sep12-09, 04:38 PM
Yes, const is a must in C++.
Thanks
Matt
Woe is me. Const ref works like a charm.
vBulletin® v3.7.6, Copyright ©2000-2009, Jelsoft Enterprises Ltd.