简体   繁体   English

C ++在子类中调用虚方法

[英]C++ call virtual method in child class

i have the following classes: 我有以下课程:

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

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

When I use inner->doSomething() I get a segmentation fault. 当我使用inner->doSomething()我得到了一个分段错误。 What should I do in order to call inner->doSomething() in the B class? 我应该怎么做才能在B类中调用inner->doSomething()

thanks in advance. 提前致谢。

Without an explicit initialization of the member inner, it's possible for it to be both not NULL and point to invalid memory. 如果没有成员内部的显式初始化,它可能既不是NULL也不是指向无效的内存。 Can you show us the code that explicitly initalizes inner? 你能告诉我们明确内在化的代码吗?

An appropriate constructor for A would be the following A的适当构造函数如下

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

though if you assign the A* to be the same as the B initialised this pointer you'll get a stack overflow ... Any reason you need the inner? 虽然如果你指定A *与B初始化这个指针相同,你会得到一个堆栈溢出...你需要内部的任何理由吗? Can't you just call A::DoSomething()? 你不能只调用A :: DoSomething()吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM