gpt4 book ai didi

c++ - 使用 dynamic_cast 向下转型返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:55:58 26 4
gpt4 key购买 nike

我尝试使用 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?

是的,你可以,例如如果 a 恰好指向 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 std::bad_cast is thrown.

关于c++ - 使用 dynamic_cast 向下转型返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com