向下转换使用 dynamic_cast returns null
Downcasting using dynamic_cast returns null
我正在尝试将基础 class 对象转换为具有 dynamic_cast
的派生 class 对象,但 dynamic_cast
returns 为空。是否可以使用 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;
}
}
此代码打印出 "no value"。
因为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.
即每个设计。 dynamic_cast 用于测试指向基 class 对象的指针是否实际指向子 class 对象。如果它是一个 subclass 对象,那么 dynamic_cast 会给你一个有效的指针,如果不是,你就得到一个 nullptr
.
由于您创建了 A
class 对象,并且 A
不是 B
的子 class,因此 dynamic_cast通常返回空指针。
我正在尝试将基础 class 对象转换为具有 dynamic_cast
的派生 class 对象,但 dynamic_cast
returns 为空。是否可以使用 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;
}
}
此代码打印出 "no value"。
因为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.
即每个设计。 dynamic_cast 用于测试指向基 class 对象的指针是否实际指向子 class 对象。如果它是一个 subclass 对象,那么 dynamic_cast 会给你一个有效的指针,如果不是,你就得到一个 nullptr
.
由于您创建了 A
class 对象,并且 A
不是 B
的子 class,因此 dynamic_cast通常返回空指针。