c++ - 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 B
type 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();
}
}
解决方案
如您所见,此代码不会编译,因为A
没有f
方法。为了使它工作,你必须明确地向下转换指针:
B* tmp = dynamic_cast<B*>(v);
tmp->f();
推荐阅读
- java - 如何将时间转换为 UTC,然后转换为设备本地时间
- python - ModuleNotFoundError:没有名为“mylife.wsgi”的模块
- javascript - 为什么我对(this.ingredients)没有定义?
- swift - 当我们在 iOS13 中关闭模式时没有调用生命周期方法
- webpack - 将 QuillJs 与 Webpack 捆绑会导致错误
- c++ - 我不断收到错误 C2248:无法访问在类中声明的私有成员
- python - 如何在递归函数中只运行一次语句
- django - 通过django代码为一对多字段赋值
- ruby-on-rails - Rails 中的宝石冲突与 Activesupport
- git - 无法检索 git stash - 即使在重复尝试和提交后文件也不会合并