加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用dynamic_cast进行向下转换返回null

发布时间:2020-12-16 10:44:33 所属栏目:百科 来源:网络整理
导读:我正在尝试使用dynamic_cast将基类对象强制转换为派生类对象,但dynamic_cast返回null.是否可以使用dynamic_cast进行向下转换? struct A { virtual ~A() {}};struct B : A {};int main(){ A* a = new A(); B* b = dynamic_castB*(a); if(b){ std::cout "b ha
我正在尝试使用dynamic_cast将基类对象强制转换为派生类对象,但dynamic_cast返回null.是否可以使用dynamic_cast进行向下转换?

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

struct B : A {};


int main()
{
    A* a = new A();

    B* b = dynamic_cast<B*>(a);
    if(b){
      std::cout << "b has value" << std::endl;
    }else{
      std::cout << "no value" << std::endl;
    }
}

此代码打印出“无价值”.

解决方法

因为a实际上指的是A而不是B,所以dynamic_cast将会失败.

Is it possible to downcast using dynamic_cast?

是的,你可以,例如,如果指向B的确切,

A* a = new B;
B* b = dynamic_cast<B*>(a);

见http://en.cppreference.com/w/cpp/language/dynamic_cast

5) If expression is a pointer or reference to a polymorphic type Base,and new_type is a pointer or reference to the type Derived a run-time check is performed:

a) The most derived object pointed/identified by expression is examined. If,in that object,expression points/refers to a public base of Derived,and if only one subobject of Derived type is derived from the subobject pointed/identified by expression,then the result of the cast points/refers to that Derived subobject. (This is known as a “downcast”.)

c) Otherwise,the runtime check fails. If the dynamic_cast is used on pointers,the null pointer value of type new_type is returned. If it was used on references,the exception 07001 is thrown.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读