指向基 class 的指针数组:如何调用唯一的派生 class 方法
Array of pointers to base class: how to call unique derived class method
在谷歌上搜索了一段时间,但似乎找不到明确的答案。
如何在下面的例子中调用 unscramble() 方法?
谢谢。 :^)
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 << "\n\n";
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();
在谷歌上搜索了一段时间,但似乎找不到明确的答案。
如何在下面的例子中调用 unscramble() 方法?
谢谢。 :^)
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 << "\n\n";
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();