[英]What happens when static_cast from derived class to base class?
While reading the C++ standard, I read that static_cast
is a kind of direct initialization (C++ standard 8.5/15). 在阅读C ++标准时,我读到
static_cast
是一种直接初始化 (C ++标准8.5 / 15)。
I think this means that during a static_cast
, the corresponding overloaded constructor is called. 我认为这意味着在
static_cast
期间,会调用相应的重载构造函数 。
For example, there is a type B and type D derived from B, and an object D d
. 例如,存在从B导出的类型B和类型D,以及对象
D d
。 Then the expression static_cast<B>(d)
is a static_cast
expression. 然后表达式
static_cast<B>(d)
是static_cast
表达式。
As the standard means, this static_cast
expression is a direct initialization . 作为标准手段,此
static_cast
表达式是直接初始化 。 Does it mean that this will call the constructor of type B
and return a new constructed object of type B
? 这是否意味着这将调用类的构造函数
B
和返回类型的新构造的对象B
?
EDIT 编辑
Another issue is how about B & b = d
or B b = d
? 另一个问题是
B & b = d
或B b = d
怎么样? Does these two statements involve constructor of B
? 这两个语句是否涉及
B
构造函数?
What they mean in the standard is that you can cast for example a float to an integer. 它们在标准中的含义是您可以将float转换为整数。 At this point conversion will happen.
此时转换将发生。 You can say that the resulting
int
is directly initialized at this point. 您可以说此时直接初始化了结果
int
。
If class that participates in casting have corresponding overloaded conversion, then yes, it will be called. 如果参与转换的类具有相应的重载转换,则是,它将被调用。 I personally would not recommend to actively use this feature.
我个人不建议积极使用此功能。 Your code will be difficult to read.
您的代码将难以阅读。
是的,对象类型的static_cast
(即,不是对引用或指针类型的static_cast
转换)将使用适当的构造函数来创建临时对象。
不。直接初始化意味着将从类D的对象复制B类对象中的每个字节,而不需要构造函数调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.