基类到子类的强制转换问题,管理员(刚才那个帖子忘了给分,可以删掉,不好意思)

fibers 2007-12-11 09:21:14
假如有如下关系:
class a{};
class b:public a
{
private: int x;
public: b(); int method1()const{return x;}
};
class c:public b
{
private: char ar[10];
public:c(); const char * method2(){return ar;}
};

b obj1;
b * pb = & obj1;
c * pc;
pc = dynamic_cast <c*> (pb);
pc-> method2(); // pc可以调用method2方法么?????

这种基类到子类的向下转换是怎么执行的??比如说子类对象里有基类对象没有的char 型私有成员以及method2()方法。。在向下转换的时候。会自动生成这些成员?
还是说忽略这些成员?
...全文
160 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
ttkk_2007 2008-01-05
  • 打赏
  • 举报
回复

b obj1;
b * pb = & obj1;
c * pc;
pc = dynamic_cast <c*> (pb);
pc-> method2(); // pc可以调用method2方法么?????


这种根本不能向下转换,pc肯定为NULL,b要有virtual函数

b *pb = new c;
c *pc = dynamic_cast<c*>(pb);
goodmrning 2008-01-04
  • 打赏
  • 举报
回复
接分!!!!
帮楼主顶下
SimonFu 2007-12-11
  • 打赏
  • 举报
回复
如果你强制转换了,存储空间是将基类当子类型读取,编译器认为数据存在
ryfdizuo 2007-12-11
  • 打赏
  • 举报
回复

dynamic_cast
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:

class CBase { };
class CDerived: public CBase { };

CBase b; CBase* pb;
CDerived d; CDerived* pd;

pb = dynamic_cast<CBase*>(&d); // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b); // wrong: base-to-derived



The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:

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

class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };

int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;

pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;

pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;

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


SimonFu 2007-12-11
  • 打赏
  • 举报
回复
dynamic_cast是用于将子类的指针(引用)转为基类的对象的指针(引用)吧,这样才是安全的
ckt 2007-12-11
  • 打赏
  • 举报
回复
你的转换很有问题,
1.类b至少要有一个virtual,才能实现多态。
2.dynamic_cast是用于将基类的指针(引用)转为子类的对象的指针(引用)

64,688

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧