【问题标题】:C++ dynamic cast with inheritance具有继承的 C++ 动态转换
【发布时间】:2016-11-11 18:57:39
【问题描述】:
#include <iostream>

using namespace std;

class A
{
public:
    void foo() { cout << "foo in A" << endl; }
};

class B : public A
{
public:
    void foo() { cout << "foo in B" << endl; }
};


int main() {
    A* a = new B;
    a->foo(); // will print "foo in A" because foo is not virtual
    B* b = new B;
    b->foo(); // will print "foo in B" because static type of b is B

    // the problem
    A* ab;
    ab = dynamic_cast<B*>(new B);
    ab->foo(); // will print "foo in A" !!!!!
}

'dynamic_cast' 不会改变 ab 的静态类型吗?我的意思是,从逻辑上讲,它接缝相当于 B* ab = new B;因为铸造..但事实并非如此。
我认为动态转换会改变对象的静态类型,我错了吗?如果是这样,有什么区别:

A* ab = dynamic_cast<B*>(new B);

A* ab = new B;  

谢谢

【问题讨论】:

  • 想想dynamic_cast&lt;B*&gt; 被应用于什么。 new B的类型是什么?

标签: c++ inheritance casting dynamic-cast


【解决方案1】:

dynamic_casting 给 B,但在分配给 ab 的时候,你隐式投射回 A,所以 dynamic_cast 再次丢失。

ab 指向的对象的实际类型仍然是 B,但访问对象的指针是 A 类型,因此选择了 A::foo。不过,如果 foo 是虚拟的,情况会有所不同。

【讨论】:

    【解决方案2】:

    如果从 A 指针调用 foo() 函数,则会调用 A 类的 foo()。我相信您正在寻找一种虚拟行为。 如果是这种情况,将 A 类的 foo() 声明为:

    virtual void foo() { cout << "foo in A" << endl; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多