【发布时间】:2019-10-17 23:22:14
【问题描述】:
我有一个简单的继承结构:
- 基础
- 基础
我想重载 > 运算符来输入和打印对象 Derived1 和 Derived2 类中的数据作为对 Base 类的引用。
我可以声明某种虚函数吗?像这样:
virtual std::ostream& operator<<(std::ostream& os, const Base& obj) = 0;
virtual std::istream& operator>>(std::istream& is, Base& obj) = 0;
在我的Base 类中,并在Derived1 和Derived2 类中覆盖它们?
我想做一些类似的事情:
std::vector<Base&> a;
... push reference to Derived1 and Derived2 objects ...
for (auto i = a.begin(); i != a.end(); ++i) std::cin >> (*i);
for (auto i = a.begin(); i != a.end(); ++i) std::cout << (*i);
【问题讨论】:
-
std::ostream& operator<<(std::ostream& os, const Base& obj) = 0;重载operator <<的std::ostream类,而不是Base类。如果你有这个想法,答案就会很清楚。 -
@AlgirdasPreidžius,我知道。但我仍然想获得该运算符的重载版本,我可以在基类引用中调用
-
嗯,看起来不错。你试过了吗?你有什么错误吗?
标签: c++ operator-overloading virtual