C ++ dynamic_cast运行时错误

时间:2014-03-08 19:32:35

标签: c++ class inheritance runtime-error dynamic-cast

我使用dynamic_cast编写了一个小应用程序来确定它是基于类还是子类,并根据它调用函数。但是当孩子上课的时候 运行,它显示它的功能两次,不知道为什么它这样做。

#include <iostream>
using namespace std;

class Base{
public:
    virtual void setting(){
        cout << "Hello, I am a function from the base class" << endl;
    }
    virtual void say(){
        cout << "Base class says hi" << endl;
    }
};

class Child:public Base{
public:
    void setting(){
        cout << "Hello, I am a function from the child class" << endl;
    }
    void say(){
        cout << "Child class says hi" << endl;
    }
};

void Ready(Base* input){
    Base* bp = dynamic_cast<Base*>(input);
    if(bp){
        bp->setting();
        bp->say();
    }
    Child* cp = dynamic_cast<Child*>(input);
    if(cp){
        cp->say();
        cp->setting();
    }
}

int main(){
    Base b;
    Child c;
    Ready(&b);
    cout << endl;
    Ready(&c); //runs twice for some reason
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:3)

当您将Child指针传递给Ready函数时,dynamic_casts都成功。 ChildBaseChild

这是一个简化的例子:

struct Foo
{
  virtual ~Foo() {}
};

struct Bar : Foo {};

#include <iostream>

int main()
{
  Bar b;
  std::cout << dynamic_cast<Foo*>(&b) << std::endl;
  std::cout << dynamic_cast<Bar*>(&b) << std::endl;
}