Bar*_*hor 6 c++ polymorphism inheritance operator-overloading
以下是代码外观的粗略示例,问题是如何让DerivedOne和DerivedTwo具有重载的<<运算符,但将这些对象存储在Base*的向量中.
至于我想要达到的目标; 我希望能够遍历对象向量并输出我在DerivedOne和DerivedTwo中告诉它的信息.
vector<Base*> objects;
class Base
{
private:
object Data
public:
object getData() { return Data; }
};
class DerivedOne : public Base
{
}
class DerivedTwo : public Base
{
}
Run Code Online (Sandbox Code Playgroud)
现在我知道有这个,但它不适用于我的目的.
friend ostream &operator<<(ostream &stream, Object object)
{
return stream << "Test" << endl;
}
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 13
使您的虚方法成为私有,以便将对象的使用方式与派生类的行为自定义方式分开.
这与其他答案解决方案类似,但虚拟方法是私有的:
#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"; }
};
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
hi One
One
bye One
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
struct Base {
virtual ~Base () {}
virtual std::ostream & output (std::ostream &) const = 0;
};
std::ostream & operator << (std::ostream &os, const Base &b) {
return b.output(os);
}
Run Code Online (Sandbox Code Playgroud)
然后,当应用operator<<
on时Base
,它将调用派生的输出方法.
归档时间: |
|
查看次数: |
4255 次 |
最近记录: |