tags:

views:

135

answers:

1

I'm trying to learn overriding operators in C++. But I'm stuck with this:

..\src\application.cpp: In function `int main()':

..\src\application.cpp:29: error: no match for 'operator<<' in 'std::operator<< >&">with _Traits = std::char_traits(&std::cout)), ((const char*)"Poly A: ")) << (&A)->Poly::operator++(0)'

Here's the line causing the error, It seems that my postincrement operator isn't returning anything printable:

cout << "Poly A: " << A++ << endl;

I have a Poly.h and a Poly.cpp file:

class Poly{
friend istream& operator>>(istream &in, Poly &robject);
friend ostream& operator<<(ostream &out, Poly &robject);
public:
 Poly();

 Poly operator++(int);
 Poly operator++();  
private:
 int data[2];
};

Poly.cpp:

Poly Poly::operator++ (){
data[0]+=1;
data[1]+=1;
return *this;}

Poly  Poly::operator++ (int){
    Poly  result(data[0], data[1]);
     ++(*this); 
    return result;
}
ostream& operator<<(ostream &out, Poly &robject){ 
out << "(" << robject.data[0] << ", " << robject.data[1] << ")";
return out;
}
+4  A: 

I think the problem is that you declare your parameters as references:

ostream& operator<<(ostream &out, Poly &robject)

The reference will not bind to the temporaries that you return from your operator++. If you make the Poly parameter a const reference you should be able to output it.

CAdaker
oh, so that's what const does. it worked thanks.
zero juan
Yes, this is correct. You need to use either a copy of Poly or a const reference (preferred) in the operator<<() function.
Andrey
Among other things. It will be a problem if one wants to both bind to a temporary and modify it, but that's not a problem in this case.
CAdaker