鉴于以下问题:
class Instrument {
};
class Guitar : public Instrument {
public:
void doGuitar() const;
};
class Piano : public Instrument {
public:
void doPiano() const;
};
我有一个指针列表Instrument
list<shared_ptr<Instrument>> instruments;
我在其中添加乐器(例如)
Guitar myGuitar;
instruments.push_back(make_shared<Guitar>(myGuitar));
现在,我想遍历列表instruments
并调用doPiano()
当且当当前乐器是钢琴并且doGuitar()
当当当当它是吉他时。这两个函数有很大不同,因此不能在 class 中抽象化Instrument
。
问题是 C++ 将无法 Instrument
通过运行时识别类型,不是吗(由于单次调度)?根据迭代器指向的当前类型,如何实现它调用钢琴或吉他功能。
如果我能实现某事,我会很高兴。像这样的伪代码工作:
list<shared_ptr<Instrument>>::const_iterator it;
if ("current type == Guitar")
(*it)->doGuitar();
else if ("current type == Piano")
(*it)->doPiano();
结果
实际上,我的方法遇到了几个问题。我使用这篇文章做了很多重构:How do do one downcast a std::shared_ptr? . 感谢大家的帮助 :)