【问题标题】:Calling virtual methods of unknown child class调用未知子类的虚方法
【发布时间】:2016-02-14 21:49:45
【问题描述】:

我有以下设置:

class Parent {
    virtual void foo(int x) = 0;
};
class Son : public Parent {
    void foo(int x) {};
};
class Daughter : public Parent {
    virtual void foo(int x) {};
};

如果我有 vector<Parent> parents 并且我正在遍历带有循环的向量,如下所示:

for (int i = 0; i < parents.size(); i++) {
    Parent s = parents[i];
    s.foo(-1);  
}

我如何称呼孩子的 foo(他们可能是儿子或女儿)?我目前遇到两个错误:

  1. Variable type 'Parent' is an abstract
  2. Variable type 'Parent' is an abstract class

【问题讨论】:

  • @Barry 修复了推导,这只是我的问题中的一个错字,而不是真正的代码。

标签: c++ polymorphism abstract-class virtual-functions


【解决方案1】:

首先,您必须使SonDaughter 成为Parent 的派生类:

class Son : public Parent {
    ...
};
class Daughter : public Parent {
    ...
};

然后,要拥有多态对象的向量,您不能在其中存储对象。您必须采用指向对象的指针向量才能使多态性起作用。

vector<Parent*> parents;

或更好:

vector<shared_ptr<Parent>> parents;

为什么?

  • 不能实例化父对象,因为它是一个抽象类。您只能创建它的派生类。
  • 如果 Parent 不是抽象的,您的代码可以工作,但是通过将 Son 或 Daughter 放入向量中,它将是 sliced

【讨论】:

  • 我刚刚省略了 : public Parent 部分。现在解决这个问题。
猜你喜欢
  • 2011-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
相关资源
最近更新 更多