Как мы можем сделать универсальный перегруженный оператор <<?</p>
Я написал этот код, но ясно, что в нем есть ошибки - отсутствует указатель типа - предполагается, что int.Примечание: C ++ не поддерживает 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();
}
Что здесь можно сделать?
Редактировать: "int i" заменено на приватного члена
Ответ:Функция друга должна быть объявлена таким образом в классе a и классе b:
template<class t>
friend ostream& operator<< <>(ostream& o,const t& obj);