从基类调用派生类构造函数

时间:2016-12-06 18:30:28

标签: c++ polymorphism

给定这段代码,(我使用不同的代码与构造函数,析构函数,虚函数等),如何实现A :: createChild,它将指针添加到B或C

#include <vector>
#include <cassert>

class A {
    void createChild(std::vector<A *>);
};

void A::createChild(std::vector<A *>) {
    //What code goes here?
}

class B : A {};

class C : A {};

int main() {
    std::vector<A *> ptrs;
    ptrs.push_back(new B);
    ptrs.push_back(new C);
    ptrs[0]->createChild(ptrs); //Should add a new class of B to ptrs
    ptrs[1]->createChild(ptrs); //Should add a new class of C to ptrs
    assert(typeid(ptrs[2])==typeid(ptrs[0]);
    assert(typeid(ptrs[3])==typeid(ptrs[1]);
}

1 个答案:

答案 0 :(得分:3)

您可以使用模板功能来实现:

class A {
    template<typename Derived>
    void createChild(std::vector<A *>);
};

template<typename Derived>
void A::createChild(std::vector<A *> v) {
    v.push_back(new Derived);
}