基类的指针数组:如何调用唯一的派生类方法

Array of pointers to base class: how to call unique derived class method

本文关键字:调用 唯一 派生 类方法 何调用 数组 指针 基类      更新时间:2023-10-16

我在谷歌上搜索了一段时间,但似乎找不到明确的答案。

我该如何调用下面示例中的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();