How can we make a generic overloaded operator<< ?
I wrote this code but clearly it has errors – missing type specifier – int assumed. Note: C++ does not support default-int.
class b{
private:
int i;
public:
b(){}
b(const int& ii):i(ii){}
friend ostream& operator<<(ostream& o,const t& obj);//Error here
};
class a:public b{
private:
int i;
int x;
public:
a(){}
a(const int& ii,const int& xx):i(ii),x(xx){}
friend ostream& operator<<(ostream& o,const t& obj);//Error here
};
template<class t>
ostream& operator<<(ostream& o,const t& obj){
o<<obj.i;
return o;
}
int main()
{
b b1(9);
a a1(8,6);
cout<<a1<<endl<<b1;
_getch();
}
What can be done here?
Edit: Changed “int i” to a private member
Answer:
friend function needs to be declared this way in class a and class b:
template<class t>
friend ostream& operator<< <>(ostream& o,const t& obj);
Put
template<class t>into thefrienddeclaration as well.I wouldn’t design
operator<<this way, however – why would it need access to private members? Better add a getter forito bothaandband avoid the socializing stuff altogether.Edit In the given code the
frienddeclarations would not even be required asiispublicin both cases. I based my answer on the presumption that they are intended to beprivatebecause otherwise being friends makes no sense here.