[英]downcasting using static_cast - pointers and objects
say I have the following class types 说我有以下类类型
class base
{
};
class der : public base
{
};
With static_Cast you can use objects and pointers. 使用static_Cast,您可以使用对象和指针。
I tried the following - which works (pointers) 我试过以下 - 哪个有效(指针)
base* b = new base();
der * m = static_cast<der*>(b);
However the following does not work 但是以下不起作用
base b;
der m = static_cast<der>(b);
Any suggestions why the second does not work ? 有什么建议为什么第二个不起作用? Doesn't static cast deal with pointers and objects ?
静态转换不处理指针和对象吗? It works with pointers but it doesnt work with the object ?
它适用于指针,但它不能与对象一起使用?
In the first one, you are saying "I have a pointer, and I promise it's pointing at a der
, so please just go with it". 在第一个,你说“我有一个指针,我保证它的指向一个
der
,所以请刚去用它。” 1 1
In the second one, you can make no such promise, because you unambiguously have a base
, not a der
. 在第二个,你可以没有这样的承诺,因为你明确地有一个
base
,而不是der
。
der
, you'll get undefined behaviour at runtime.
der
,您将获得在运行时不确定的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.