probblem in operator overloading(>>&<<) in c++

#include<conio.h>
#include<stdio.h>
struct input
{
void operator>>(int&x)
{
scanf("%d",&x);
return;
}
};
struct output
{
void operator<<(char* str)
{
printf(str);
return;
}
void operator<<(int x)
{
printf("%d",x);
return;
}
};
int main(void)
{
input in;
output out;
clrscr();
int x=0,y=0,z=0;
out<<"enter two number";
/*the code given below gives error msg not an allowed type*/
/* in>>x>>y;[->error not an allowed type]
out<<x<<y;[->error not an allowed type]*/
/*but if i write this code in place of the of the above given code then it works*/
in>>x;
in>>y;
out<<x;
out<<y;
z=x+y;
out<<z;
while(!kbhit());
return 0;
}
Last edited on
The problem is that your operators return nothing. They have to return (a reference to) the object.
cout << 1 << 2; works because cout is an object that has an operator << overloaded and (cout << 1) returns an object that has operator << overloaded (it returns a reference to itself).

By the way, in the future, put your code in [code] tags and write what exactly is wrong.
I've done some overloading of these recently. You have two problems:

first you only have one argument (int x). The << and >> operators take two arguments representing the object on the left (cout, cin) and the object on the right (int, char*) .

Second, you need to return the same object that was used on the left side of the equation. This lets us chain multiple operators togeather.

The trick is to define a return type, and two arguments.

example:
&ostream operator << (&ostream os, int x)

This lets us put an integer into an ostream object (like cout). It then returns that ostream object so it can be used again in a chain.
Last edited on
When you put your overloaded operator inside a class (struct, in this case), you only need to write the second argument. The first one is implicitly this.
thanx for the reply gentleman......
@hamsterman sir when we put our overloaded operator inside a class then its first argument is implicitly "this" then how we can return reference of its object so that this line of code work properly.........
ex
in>>x>>y;
or
out<<x<<y;
1
2
3
4
input& operator>>(int &x){
//...
  return *this;
}
Topic archived. No new replies allowed.