首页 > 解决方案 > C ++如何从父级调用子方法

问题描述

我正在做一个小项目,我发现自己处于这样的情况:

class A{}

class B : class A {
    public:
        void f();
        int getType() const;
    private:
        int type;
}

class C : class A{
    public:
        int getType() const;
    private:
        int type;
}

我想知道是否有办法从一个对象调用f()函数) ?(in class Btype A

我试过了,但它说f()在以下位置找不到函数class A

int main(){
    vector<A*> v;
    // v initialized with values of A ...
    if (v->getType() == 1){             // 1 is the type of B
        v->f();
    }
}

标签: c++inheritancecompiler-errorspure-virtual

解决方案


如您所见,此代码不会编译,因为A没有f方法。为了使它工作,你必须明确地向下转换指针:

B* tmp = dynamic_cast<B*>(v);
tmp->f();

推荐阅读