#include<iostream.h>
#include<conio.h>
class time
{
private:
int dd,mm,yy;
public:
friend istream & operator >>(istream &ip,time &t)
{
cout<<"\nEnter Date";
ip>>t.dd;
cout<<"\nEnter Month";
ip>>t.mm;
cout<<"\nEnter Year";
ip>>t.yy;
return ip;
}
friend ostream & operator <<(ostream &op,time &t)
{
op<<t.dd<<"/"<<t.mm<<"/"<<t.yy;
return op;
}
void validate();
};
void time::validate()
{
}
int main()
{
clrscr();
time t1;
cin>>t1;
cout<<t1;
getch();
return 0;
}
What difference does it make? When I define the friend function outside the class the compiler is giving an error but when I define it inside a class it works perfectly fine.
Note: I am using Turbo C++. I know that's old school, but we are bound to use that.
The problem is, that you are accessing private members of your class (dd,mm,yy), what is only allowed for functions of that class or friends. So you have to declare the function a friend inside of the class and than it can be implemented outside of the class.
class time
{
private:
int dd,mm,yy;
public:
friend istream & operator >>(istream &ip,time &t); // declare function as friend to allow private memeber access
friend ostream & operator <<(ostream &op,time &t); // declare function as friend to allow private memeber access
void validate();
};
Now you can write the implementation outside of the class and access private variables.
istream & operator >>(istream &ip,time &t)
{
cout<<"\nEnter Date";
ip>>t.dd;
cout<<"\nEnter Month";
ip>>t.mm;
cout<<"\nEnter Year";
ip>>t.yy;
return ip;
}
ostream & operator <<(ostream &op,time &t)
{
op<<t.dd<<"/"<<t.mm<<"/"<<t.yy;
return op;
}