小编use*_*123的帖子

使用在堆栈上创建的对象调用虚拟函数

我有一个带有两个函数的简单CTest类- func()和virtualFunc()。我仅出于测试目的而在堆栈上创建一个对象,并希望观察其行为。我确实意识到我们应该new在堆上使用关键字创建一个对象,但是我对知道对象在堆栈上时虚函数的行为很感兴趣。

使用我当前拥有的代码,当我尝试调用虚拟函数时会导致Seg Fault。谁能告诉我为什么虚拟功能导致段错误而非虚拟功能却没有?

class CTest {
    public:
        void func() {
            printf("function was called.\n");
        }   
        virtual void virtualFunc() {
            printf("virtual function was called.\n");
        }   
};

int main (int argc, char ** argv) {
    CTest * obj = NULL;

    obj->func(); // this would print "function called" as what's inside the func()

    obj->virtualFunc(); 
    //line above results in segfault because C *obj is on stack; 
    //You would need to allocated obj on the heap for the virtual function …
Run Code Online (Sandbox Code Playgroud)

c++ virtual-functions segmentation-fault

-1
推荐指数
1
解决办法
34
查看次数