c++ - 虚函数调用段错误

标签 c++ segmentation-fault virtual-functions vtable

每当我尝试访问虚函数时,我都会遇到段错误。代码基本上是这样的:

class Super {
  public:
    Super() { cout << "Ctor Super" << endl; }
    virtual void test() = 0;
  };

class Sub : public Super {
  public:
    Sub() { cout << "Ctor Sub" << endl; }
    void test() { cout << "Test in Sub" << endl; }
  };

void main()
 {
   Super* s = new Sub;
   s->test(); // Segmentation fault So I tried the one below

   Sub* s1 = new Sub;
   s1->test(); //Still segmentation fault

   Sub s2;
   s2.test(); // Works fine BUT

   Super *s3 = &s2;
   s3->test(); // segmentation fault and EVEN

   Sub *s4 = &s2;
   s4->test(); //segmentation fault
 }

我几乎尝试了我所知道的关于虚函数的一切,但它不起作用。它实际上是一个更大程序的一部分,所以它可能在那里有一些问题,但只要我删除虚拟功能或停止将其虚拟化,它就会工作。有什么想法吗?

还有什么工具或方法可以检查虚表吗?

最佳答案

Sub 类不继承自 Super 类,因此它们在当前编写的任何方面都不相关。

关于c++ - 虚函数调用段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5611557/

相关文章:

c++ - std::mutex 和 std::condition_variable 构造开销与堆分配

javascript - node.js 和段错误

c++ - 线程和模板成员函数

Linux 的 C++ 对象序列化

c++ - 如何显示大于某个值的数字?

使用长整数的 C 段错误

linux - 微小的 "manually"创建的 ELF 给出了段错误

c++ - 派生类的成员函数是否继承了基类的虚拟性?

c++ - 在C++中,是否有可能在父类(super class)中有一个方法,当每个子类调用该方法时,该方法会向该子类返回一个shared_ptr?

c++ - 从文件中读取对象后无法调用虚拟成员函数