@H_403_8@
@H_403_8@
A dynamic_cast has the following form:@H_403_8@
dynamic_cast<type*>(e)dynamic_cast<type&>(e)dynamic_cast<type&&>(e)
where type must be a class type and (ordinarily) names a class that has virtual
functions. In the first case,e
must be a valID pointer (§ 2.3.2,p. 52); in the second,e
must be an lvalue; and in the third,e
must not be an lvalue. @H_403_8@In all cases,the type of
e
must be either a class type that is publicly derived from
the target type,a public base class of the target type,or the same as the target
type. Ife
has one of these types,then the cast will succeed. Otherwise,the cast fails.
If a dynamic_cast to a pointer type fails,the result is 0. If a dynamic_cast to a
reference type fails,the operator throws an exception of typebad_cast
@H_403_8@
但是,我在这里写了一段代码片段:@H_403_8@
@H_403_8@
struct A {};struct B : private A // note: *private* inheritance{ A* test() { return dynamic_cast<A*>(this); }};int main(){ B b; if(b.test()==nullptr) throw 1;}
在上面的代码片段中,A只是B的私有基础,c引物不考虑它.但是,此代码段可以编译并运行而不会出错.底漆有错吗?@H_403_8@解决方法 这一切都是引物部分的一个不幸的措辞.它将两种类型的演员阵容组合成一个句子,然后错过了结果.
@H_403_8@
转换为基类,不需要运行时强制转换 *** 作.它是,as T.C. says,纯粹是一个静态结构.和T.C.一样.引用它,它需要一个accessbile基础,而不是公共基础.所以你的代码一切都很好.@H_403_8@
对于运行时强制转换(向下转换),C标准对 *** 作数和动态强制转换中涉及的类型提出了要求,以使其成功.该类必须是公开派生的,否则实现没有义务成功转换继承链.我的意思是,它理论上可以使演员成功,但根据规范“the runtime check fails”,这并没有留下太多的余地.@H_403_8@
但无论哪种方式,你的程序都没有任何错误会使它无法编译,也没有任何东西会导致任何类型的运行时错误.@H_403_8@
如果我们将您的代码更改为强制转换而不是强制转换,则此处为example that doesn’t even build:@H_403_8@
@H_403_8@
struct A {};struct B : private A // note: *private* inheritance{ A* test(B* p) { return dynamic_cast<A*>(p); } frIEnd B* foo(A*);};B* foo(A* a) { return dynamic_cast<B*>(a);}int main(){ B b; *foo(&b);}
A是foo中B的可访问基础,然而,演员阵容是不正确的.@H_403_8@
将引物重新引入过程的最小变化是将“从目标类型公开派生的类类型”变为“从目标类型可访问地派生的类类型”.由于publicly available errata中没有任何类型,我们可以猜测这是一个尚未被指出的编辑错误.@H_403_8@ 总结
以上是内存溢出为你收集整理的使用`dynamic_cast`时,c底漆是否有问题?全部内容,希望文章能够帮你解决使用`dynamic_cast`时,c底漆是否有问题?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)