什么是有效的完整对象呢?

时间:2014-09-10 06:56:49

标签: c++

我对此部分感到困惑 虽然我们使用dynamic_cast来确保指针之间的转换结果是目标类型的有效完整对象,但我无法获得有效完整对象的含义 这是示例

#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {}


 };
class Derived: public Base {public:
void print(){cout << "NiGHt!\n";
 int a; };

int main () {
try {
Base * pba = new Derived;
Base * pbb = new Base;
Derived * pd;

pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";

pd = dynamic_cast<Derived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast.\n";

 } catch (exception& e) {cout << "Exception: " << e.what();}

 return 0;
}

如果这两行表示转换结果成功那么为什么我不能使用指针pba进入Derived类?

pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";

1 个答案:

答案 0 :(得分:0)

pd = dynamic_cast<Derived*>(pba);表示强制转换pba指针(指向Base类的指针,但它包含Derived对象,因为:{{1} })指向Base * pba = new Derived对象的指针。如果DerivedBase之间没有关系(即:Derived必须从Derived派生)并且将返回0,则此演员表将失败。

为什么不能使用Base获取pba课程?因为Derived是指向pba类的指针。所以它根本不知道有Base类。

参考:When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?