[C++] 纯文本查看 复制代码
Base *bp, b_ob;
Derived *dp, d_ob;
bp = &d_ob; // 基类型的指针可以指向派生类的对象
dp = dynamic_cast<Derived *> (bp); //强制转换基类指针为派生类指针,做法正确
[C++] 纯文本查看 复制代码
// dynamicast.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Base {
public:
virtual void f() { cout << "Inside Base.\n"; }
};
class Derived : public Base {
public:
void f() { cout << "Inside Derived\n"; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Base *bp, b_ob;
Derived *dp, d_ob;
dp = dynamic_cast<Derived *>(&d_ob); //派生类对象的指针强制转换为派生类对象的指针 OK
if (dp) {
cout << "Cast from Derived * to Derived * OK.\n";
dp->f();
} else
cout << "Error\n";
cout << endl;
bp = dynamic_cast<Base *>(&d_ob); //派生类对象的指针强制转换为基类的指针 OK(基类指针可以指向派生类的对象)
if (bp) {
cout << "Cast from Derived * to Base * OK.\n";
bp->f();
} else
cout << "Error\n";
cout << endl;
bp = dynamic_cast<Base *>(&b_ob); //基类的指针强制转换为基类的指针 OK
if (bp) {
cout << "Cast from Base * to Base * OK.\n";
bp->f();
} else
cout << "Error\n";
cout << endl;
dp = dynamic_cast<Derived *>(&b_ob); //基类对象的指针(地址)强制转换为派生类的指针(失败)
if(dp)
cout << "Error\n";
else
cout << "Cast from Base * to Derived * not OK.\n";
cout << endl;
bp = &d_ob; //bp 指向派生类的对象
dp = dynamic_cast<Derived *> (bp); //可以,因为 bp 确实已经指向了派生类
if(dp) {
cout << "Casting bp to Derived * OK\n" << "because bp is really pointing\n"
<< "to a Derived object.\n";
dp->f();
}else
cout << "Error\n";
cout << endl;
bp = &b_ob; //bp 指向基类型对象
dp = dynamic_cast<Derived *> (bp); //失败,因为 bp 现在已经确实指向了基类对象
if(dp)
cout << "Error";
else {
cout << "Now casting bp to a Derived *\n"
<< "is not OK because bp is really \n"
<< "pointing to a Base object.\n";
}
cout << endl;
dp = &d_ob; //dp 指向派生类对象
bp = dynamic_cast<Base *> (dp); //可以,基类指针可以指向派生类对象
if (bp) {
cout << "Casting dp to a Base * is OK.\n";
bp->f();
}else
cout << "Error\n";
return 0;
}