【问题标题】:C++ Inheritance virtual function crashingC++继承虚函数崩溃
【发布时间】:2013-06-26 15:07:20
【问题描述】:

我不知道为什么这段代码会崩溃,它看起来对我来说是正确的,但它只是崩溃了 SIGSEV。我来自 Java,习惯于“有用”的错误消息...

main.cpp

#include <cstdlib>
#include <stdio.h>

#include "DuckV.h"
#include "PenguinV.h" 

bool tryFlyOOP(IBird* birdy)
{
    return birdy->canFly();
}
int main(int argc, char** argv)
{
   DuckV* duckV;
   PenguinV* penguinV;

    printf("My OOP duck %s fly\n", tryFlyOOP(duckV) ? "can" : "can't");
    printf("OOP Penguins %s fly\n", tryFlyOOP(penguinV) ? "can" : "can't");

    return 0;
}

IBird:

#ifndef IBIRD_H
#define IBIRD_H

class IBird
{
public:
    IBird () {}
    virtual bool canFly() {return true;};
};

#endif  /* IBIRD_H */

DuckV/PenguinV除了名字和返回值都一样

#ifndef DUCKV_H
#define DUCKV_H

#include "IBird.h"

class DuckV : public IBird
{
public:
    DuckV(){}
    virtual bool canFly() {return true;}
};

#endif  /* DUCKV_H */

我尝试过改变一些东西,但我就是不明白。任何帮助将不胜感激:)。

【问题讨论】:

  • 将该 SIGSEV 读取为 NullPointerException

标签: c++ inheritance virtual


【解决方案1】:

你还没有初始化你的指针:

DuckV* duckV; // points to a random location. No DuckV object exists.

我建议你放弃指针并执行以下操作:

bool tryFlyOOP(const IBird& birdy)
{
    return birdy.canFly();
}

然后

DuckV duckV;
std::cout << "My OOP duck " << (tryFlyOOP(duckV) ? "can" : "can't") << " fly\n";

这将要求您将canFly() 成员函数设为const

class IBird
{
public:
    IBird () {}
    virtual bool canFly() const {return true;};
};

【讨论】:

    【解决方案2】:

    这是因为你的对象没有被创建。

    你应该这样做:

    DuckV* duckV = new DuckV();
    PenguinV* penguinV = new PenguinV();
    

    在您的代码中,您刚刚声明了指针。

    或者你可以这样做:

    DuckV duckV;
    PenguinV penguinV;
    
    bool tryFlyOOP(const IBird& birdy)
    {
        return birdy.canFly();
    }
    

    在最后一个示例中,您使用了引用,这也是一个很好的方法。

    【讨论】:

      【解决方案3】:

      您尚未初始化变量(duckV 和 penguinV)。由于您想将它们用作指针,因此请使用“new”运算符创建新对象并将其分配给这些变量。或者 - 更好的是 - 在堆栈上创建它们并传递引用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-23
        • 2015-08-07
        • 2015-06-23
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        相关资源
        最近更新 更多