【发布时间】:2013-04-26 15:55:57
【问题描述】:
考虑下面的代码:
#include <iostream>
using namespace std;
class Base{
int i;
public:
virtual bool baseTrue() {return true;}
Base(int i) {this->i=i;}
int get_i() {return i;}
};
class Derived : public Base{
int j;
public:
Derived(int i,int j) : Base(i) {this->j=j;}
int get_j() {return j;}
};
int main()
{
Base *bp;
Derived *pd,DOb(5,10);
bp = &DOb;
//We are trying to cast base class pointer to derived class pointer
cout << bp->get_i() << endl;
cout << ((Derived *)bp)->get_j() << endl;**//HERE1**
pd=dynamic_cast<Derived*> (bp); **//HERE2**
// If base class is not polymorphic
//throw error
//error: cannot dynamic_cast `bp' (of type `class Base*') to
//type `class Derived*' (source type is not polymorphic)
cout << pd->get_j() << endl;**//HERE2**
//Now we try to cast derived Class Pointer to base Class Pointer
Base *pb;
Derived *dp,Dbo(50,100);
dp = &Dbo;
cout << ((Base *)dp)->get_i() << endl;**//HERE3**
//cout << ((Base *)dp)->get_j() << endl;
//throws error Test.cpp:42: error: 'class Base' has no member named 'get_j'
pb = dynamic_cast<Base * > (dp); **//HERE4**
cout << pb->get_i() << endl; **//HERE4**
//cout << pb->get_j() << endl;
//throws error Test.cpp:47: error: 'class Base' has no member named 'get_j'
return 0;
}
输出
Gaurav@Gaurav-PC /cygdrive/d/Glaswegian/CPP/Test
$ ./Test
5
10
10
50
50
我的投射方式(行 HERE1 和 HERE2 )和(HERE3 和 HERE4),两者有什么区别?两者都产生相同的输出,那么为什么要选择 dynamic_cast
【问题讨论】:
-
可能看到这篇文章? stackoverflow.com/questions/28002/…
-
您可能会发现cplusplus.com/doc/tutorial/typecasting 很有用。它解释了您在 c++ 中的不同转换方式。
-
转换 HERE3 和 HERE4 没用,编译器可以自动完成:
bp = dp; -
@Muncken 我已经提到了那个教程。我很好奇我的代码中使用的转换类型之间的区别
-
@Gaurav 很棒。如果您还没有,那将是一个很好的开始:)
标签: c++