基类的指针数组:如何调用唯一的派生类方法
Array of pointers to base class: how to call unique derived class method
我在谷歌上搜索了一段时间,但似乎找不到明确的答案。
我该如何调用下面示例中的unsamble()方法?
谢谢。:^)
class Food {
public:
Food(string _t):type(_t);
virtual void eat() = 0;
private:
string type;
}
class Fruit : public Food {
public:
Fruit(string _t):Food(_t) {
virtual void eat() { // Yummy.. }
}
class Egg : public Food {
public:
Egg(string _t):Food(_t)};
virtual void eat() { // Delicious! };
void unscramble();
}
int main() {
Food *ptr[2];
ptr[0] = new Fruit("Apple");
ptr[1] = new Egg("Brown");
// Now, I want to call the unscramble() method on Egg.
// Note that this method is unique to the Egg class.
ptr[1]->unscramble();
// ERROR: No member "unscramble" in Food
cout << "nn";
return 0;
}
如果你确定它是鸡蛋:
static_cast<Egg*>(ptr[1])->unscramble();
如果你不知道它是否是鸡蛋:
auto egg = dynamic_cast<Egg*>(ptr[1]);
if (egg != nullptr)
egg->unscramble();
您可以通过以下方式使用dynamic_cast
:
auto e = dynamic_cast<Egg*>(ptr[1]);
if(e) e->unscramble();
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 何时在引用或唯一指针上使用移动语义
- 函数从唯一代码调用正确的子类方法
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 使用唯一指针调用函数会使我的程序崩溃
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- 在这种情况下,我应该为每个WSASend调用传递唯一的重叠结构吗?
- 空的唯一指针在离开作用域时调用析构函数
- 对宏的唯一可识别调用
- C++14 不能调用从唯一指针继承的类的复制构造函数或运算符 =
- 析构函数是移动ctor/赋值的RHS上唯一调用过的东西吗
- 方法,用于在代码中唯一标识方法调用,以测试调用序列是否未更改
- 基类的指针数组:如何调用唯一的派生类方法
- 指针类型是"prevent"声明中调用构造函数的唯一方法吗?
- Boost Python def 成员函数,它调用静态函数,其中 self 作为唯一的参数
- 从基类对象的指针向量调用派生类的唯一函数