Reputation: 175
I don't really understand why I get this error when I compile the code below:
error: no match for call to '(Integer) (int)'
a = f((int) a);
I'm always confused if I need to declare the return type of operator+
and operator=
as Integer&
or just Integer
, and when to declare a conversion operator in my class. If it's possible, what are all the implicit conversions of an object without a cast?
#include <iostream>
class Integer{
int x;
public:
Integer(int e): x(e) {};
Integer(const Integer &e): x(e.x) {};
Integer& operator=(const Integer &e) {
x = e.x;
return *this;
}
Integer& operator+(const Integer &e) {
x = x + e.x;
return *this;
}
operator int () {
return x;
}
friend std::ostream& operator<<(std::ostream &os, const Integer &e) {
return os << e.x; //corrected
}
};
int f ( int i ){
return i + 1;
}
int main (){
Integer e (1);
Integer f =2;
Integer a = e + f ;
a = f(a); //f the function
std :: cout <<"a vaut : "<<a << std :: endl ;
return 0;
}
Upvotes: 1
Views: 107
Reputation: 73366
The compilation error comes from the naming conflict between one of the variables and a function, as already pointed out by others in the comments, and in the other answer. Just rename the function or the variable.
But this is not the only problem. Once this is corrected, you will face an endless recursion in your stream inserter, because it recursively calls itself. Just correct it into:
friend std::ostream& operator<<(std::ostream &os, const Integer &e) {
return os << e.x; // not e !!!
}
Finally, it's not a problem yet, but operator+
should return a new Integer by value, and not the reference to the current object. Otherwhise, you may get some nasty surprises in more complex expressions.
Upvotes: 3
Reputation: 4096
Your error stems from having a function (int f(int)
) and an object (Integer f
) with the same name.
Since the object is closer in scope than the function the compiler tries to use it first, in particular it tries to find an operator()
overload on it that would fit the parameter a
. Since that doesn't exist it reports the error you see.
The cleanest solution would be to use clear and distinct names for objects and functions (instead of one letter names).
Assuming that for some reason you could not change them (which may happen in more complicated projects) the alternative is to use the scope resolution operator ::
- in your particular case it would be:
a = ::f(a);
Upvotes: 1