C ++在子类中调用virtual方法 [英] C++ call virtual method in child class

查看:308
本文介绍了C ++在子类中调用virtual方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

class A {
protected:
     A *inner;
public:
    ....
    virtual void doSomething() = 0;
    ....
}

class B: public A {
   ...
   void doSomething() {
       if(inner != NULL)
           inner->doSomething();
   }
   ...
}

code> inner-> doSomething()我得到一个分段错误。
为了在B类中调用 inner-> doSomething(),我该怎么办?

When I use inner->doSomething() I get a segmentation fault. What should I do in order to call inner->doSomething() in the B class?

推荐答案

没有成员内部的显式初始化,它可能既不是NULL,指向无效内存。你能告诉我们明确的内部代码吗?

Without an explicit initialization of the member inner, it's possible for it to be both not NULL and point to invalid memory. Can you show us the code that explicitly initalizes inner?

A的一个合适的构造函数如下:

An appropriate constructor for A would be the following

protected:
A() : inner(NULL) {
  ...
}

这篇关于C ++在子类中调用virtual方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆