简体   繁体   English

用结构体强制转换c ++

[英]Casting with structs c++

Can I simply cast a Parent-struct in a child-struct in c++? 我可以简单地在c ++中将父结构转换为子结构吗?

I tried to cast: 我试图投:

Base s;
Child tmp = (Child)s;

and got this error: No matching conversion for C-style cast from ... 并得到此错误:从...没有匹配的C样式转换转换...

Can anyone help me to solve this error? 谁能帮我解决这个错误?

A struct is a type consisting of a sequence of members whose storage is allocated in an ordered sequence If the sequence is a mismatch, the conversion may not work. struct是由一系列成员组成的类型,这些成员的存储按有序序列分配。如果序列不匹配,则转换可能无法进行。

Within a struct object, addresses of its elements (and the addresses of the bit field allocation units) increase in order in which the members were defined. 在结构对象中,其元素的地址(以及位字段分配单元的地址)按定义成员的顺序增加。 A pointer to a struct can be cast to a pointer to its first member (or, if the member is a bit field, to its allocation unit). 指向结构的指针可以转换为指向其第一个成员的指针(或者,如果该成员是位字段,则指向其分配单元)。 Likewise, a pointer to the first member of a struct can be cast to a pointer to the enclosing struct. 同样,指向结构的第一个成员的指针可以转换为指向封闭结构的指针。 There may be unnamed padding between any two members of a struct or after the last member, but not before the first member. 在结构的任何两个成员之间或在最后一个成员之后但在第一个成员之前可能没有未命名的填充。 The size of a struct is at least as large as the sum of the sizes of its members. 结构的大小至少与其成员大小的总和一样大。

First of all, If you are using c++. 首先,如果您使用的是c ++。 Why would you like to perform c style casting between Base and Child ? 为什么要在BaseChild之间执行c样式转换?

C++ provided static_cast for non-polymorphic conversion and dynamic_cast for the polymorphic conversion. C ++为非多态转换提供了static_cast为多态转换提供了dynamic_cast

There is more info about these casts: Regular cast vs. static_cast vs. dynamic_cast ? 有关这些转换的更多信息: 常规转换vs. static_cast与dynamic_cast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM