虚拟重载运算符>>和<< [英] Virtual overloaded operators >> and <<
本文介绍了虚拟重载运算符>>和<<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个接口,该接口要求其子类重载< 和
>>
,但是我不太确定怎么做,因为这些运算符不会作为成员函数重载:
I need an interface that would require its subclasses to overload <<
and >>
, but I'm not quite sure how since these operators aren't overloaded as member functions:
std::istream& operator>> (std::istream& in, Student& student) {
in >> student.name >> student.group;
for (int& i : student.marks) { in >> i; }
return in;
}
也许有一种使其成为成员函数的方法?
Maybe there's a way to make it a member function?
推荐答案
您可以执行以下操作:
class StudentInterface
{
public:
virtual void readSelfFrom(std::istream& in) = 0;
};
std::istream& operator>> (std::istream& in, StudentInteface& student)
{
student.readSelfFrom(in);
return in;
}
然后让用户从 StudentInterface $派生c $ c>,例如:
class Student: public StudentInterface
{
public:
void readSelfFrom(std::istream& in) override
{
in >> name >> group;
for (int& i : marks) { in >> i; }
}
};
这篇关于虚拟重载运算符>>和<<的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文