Overloaded << Operator Error ?? why

P

pallavsingh81

#include<iostream.h>

//prefix and postfix Operator overloading // Inorder to see effect
overload operator <<

class A
{
public :
int i,j;
A(int _i,int _j):i(_i),j(_j){}
A & operator++();
const A operator++(int);

};


A& A::eek:perator++()
{
this->i = this->i + 1;
this->j = this->j +1 ;
return *this;
}



const A A::eek:perator++(int)
{
A obj = *this;
this->i = this->i + 1;
this->j = this->j +1 ;

return obj;
}

ostream & operator << (ostream & out , A & obj)
{
out<<"Value of i "<<obj.i<<endl;
out<<"Value of j "<<obj.j<<endl;
return out;
}

int main()
{

A obj(10,20);
cout<<++obj;
cout<<obj++; // Error Why ????????????????

return 0;
}
 
R

Rolf Magnus

#include<iostream.h>

This is an obsolete non-standard header. You shouldn't use it.
//prefix and postfix Operator overloading // Inorder to see effect
overload operator <<

class A
{
public :
int i,j;
A(int _i,int _j):i(_i),j(_j){}
A & operator++();
const A operator++(int);

};


A& A::eek:perator++()
{
this->i = this->i + 1;
this->j = this->j +1 ;
return *this;
}



const A A::eek:perator++(int)
{
A obj = *this;
this->i = this->i + 1;
this->j = this->j +1 ;

return obj;
}

ostream & operator << (ostream & out , A & obj)

So this operator claims to modify A. Since it doesn't, the second parameter
should be a reference to const A. This will also solve your problem.
{
out<<"Value of i "<<obj.i<<endl;
out<<"Value of j "<<obj.j<<endl;
return out;
}

int main()
{

A obj(10,20);
cout<<++obj;
cout<<obj++; // Error Why ????????????????

Because the object returned by the operator is a temporary, which cannot be
bound to a non-const reference.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top