简体   繁体   English

当static_cast从派生类到基类时会发生什么?

[英]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 = dB 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.

相关问题 什么时候是`static_cast <Base*> (的static_cast <void*> (派生))`从指向派生类的指针有效吗? - When is a `static_cast<Base*>(static_cast<void*>(derived))` from a pointer to a derived class valid? 如果派生类包含其他方法和成员,那么static_cast可以从基类到派生类完成吗? - Can static_cast be done from base class to derived class if derived class contains additional methods and members? 访问存储在向量中的已知派生类对象时,使用dynamic_cast或static_cast有什么问题 <base*> ? - What's wrong with using dynamic_cast or static_cast when accessing known derived class objects stored in vector<base*>? 将派生对象中的“this”指针的static_cast用于基类的问题 - Question of using static_cast on “this” pointer in a derived object to base class "static_cast 将此对象派生到 C++ 中的基类" - static_cast derived this object to base class in C++ 从基类指针到派生类指针的static_cast无效 - static_cast from base class pointer to derived class pointer is invalid C2440 static_cast无法从基类转换为派生类 - C2440 static_cast cannot convert from base class to derived class static_cast到base析构函数的指向派生类的安全性 - Safety of static_cast to pointer-to-derived class from base destructor 如果static_cast无效值枚举类会发生什么? - What happens if you static_cast invalid value to enum class? static_cast从Derived *到void *到Base * - static_cast from Derived* to void* to Base*
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM