重载'<<'有不和谐和多态? [英] overloading '<<' with inhertiance and polymorphism?
问题描述
以下是代码外观的粗略示例,问题是如何让DerivedOne和DerivedTwo重载<<运算符,但将这些对象存储在Base *的向量中。
The following is a rough sample of what the code looks like, the question is how can I have DerivedOne and DerivedTwo have a overloaded << operator but store these objects in a vector of Base*.
至于我想要实现的目标;我希望能够遍历对象向量并输出我在DerivedOne和DerivedTwo中告诉它的信息。
As for what I want to achieve; I want to be able to loop through the objects vector and output the information that I tell it to in the DerivedOne and DerivedTwo.
vector<Base*> objects;
class Base
{
private:
object Data
public:
object getData() { return Data; }
};
class DerivedOne : public Base
{
}
class DerivedTwo : public Base
{
}
现在我知道有这个,但它不能用于我的目的。
Now I know there is this, but it wont work for my purposes.
friend ostream &operator<<(ostream &stream, Object object)
{
return stream << "Test" << endl;
}
推荐答案
将您的虚拟方法设为私有,以便将对象的使用方式与派生类的行为自定义区分开来。
这与其他答案解决方案类似,但虚拟方法是私有的:
Here's a similar to other answers solution but the virtual method is private:
#include <iostream>
namespace {
class Base {
// private (there is no need to call it in subclasses)
virtual std::ostream& doprint(std::ostream&) const = 0;
public:
friend std::ostream& operator << (std::ostream& os, const Base& b) {
return b.doprint(os); // polymorphic print via reference
}
virtual ~Base() {} // allow polymorphic delete
};
class DerivedOne : public Base {
std::ostream& doprint(std::ostream& os) const {
return os << "One";
}
public:
DerivedOne() { std::cerr << "hi " << *this << "\n"; } // use << inside class
~DerivedOne() { std::cerr << "bye " << *this << "\n"; }
};
}
示例
Example
#include <memory>
#include <vector>
int main () {
using namespace std;
// wrap Base* with shared_ptr<> to put it in a vector
vector<shared_ptr<Base>> v{ make_shared<DerivedOne>() };
for (auto i: v) cout << *i << " ";
cout << endl;
}
输出
Output
hi One
One
bye One
这篇关于重载'<<'有不和谐和多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!