在 c++ 中将一种结构类型分配给另一种类型
Assigning one structure type into another type in c++
我们知道我们只能将一个结构对象分配给另一个具有相同类型的结构对象,但为什么我们不能将一个类型为 A 的结构对象分配给另一个类型 B 的结构对象呢?
这里
struct typeA{
int inA1;
int inA2;
};
struct typeB{
int inB1;
int inB2;
};
int main(){
typeA varA;
typeB varB;
varA = varB//Here it will show compile time error. Why it can't
//assign object of typeB to object of typeA since both have
//same type of members
return 0;
}
为什么我们不能将 B 型结构的对象分配给 A 型结构的对象,因为两者都有相同类型的成员?
为什么规则是不将不同类型的结构对象分配给另一个结构对象,因为它们可能具有相同的成员?
编译器将生成一个赋值运算符来赋值相同类型的变量。但是,即使两种类型具有相同的布局,它也不会为其生成赋值运算符。这也是完全可以理解的,因为它很容易成为错误的来源。
为什么它会成为错误的根源?
好吧,想象一下,如果typeB
是这样定义的:
struct typeB{
int inB2;
int inB1;
};
很费解呵呵?即使typeA
和类型typeB
具有相同的布局,您也期望inA1
取inB1
的值,但相反的情况会发生,inA1
将采用inB2
的值。
由于名称不会影响布局,并且编译器不知道您关于该赋值应该如何执行的意图,因此它不会假设任何事情,也不会创建错误编写的赋值运算符。
因此,默认情况下不会生成您期望存在的赋值运算符,但您可以肯定地编写一个:
struct typeA{
int inA1;
int inA2;
typeA& operator=(const typeB& rhs) {
inA1 = rhs.inB1;
inA2 = rhs.inB2;
return *this;
}
};
现在,编译器知道如何以预期的方式分配它们。
作为安全手段,不能将不同的类型相互分配。虽然底层类型在字面上是兼容的,但编译器不知道语义 - 您可能不小心将某人的年龄和体重分配到他们的血压测量中。
如果你真的确定要这样做,你可以将varB强制转换为类型A:
varA = (typeA)varB;
这指示编译器非常确定要做什么,尽管在某些情况下,编译器可能会选择在检测到您可能会丢失某些携带的信息时仍然警告您,但它也可能不会。
这不是您要查找的确切答案,但是如果您不想要显式构造函数。你可以让隐式构造函数处理这种情况varA = varB;
#include <iostream>
struct typeA{
int inA1;
int inA2;
};
struct typeB : typeA
{
int inB1;
int inB2;
// implicit default ctor typeB::typeBB()
// implicit copy ctor typeB::typeB(const B&)
};
int main(){
typeA varA;
typeB varB;
varA = varB;//handled by implicit constructor
return 0;
}
相关文章:
- 没有类型结构绑定不起作用?
- 如何使用指针连接两种不同的节点类型(结构)?
- 无法汇总初始化类型结构的变量,其中包含在类模板中的位字段成员
- 您如何声明类型结构的堆栈?在C 中
- 访问指向相同类型结构的指针
- 静态数据类型(结构)的组织
- 创建类型结构的指针阵列
- 处理类型结构数组
- 嵌入式 C++:在 C++ 中初始化易失性类型结构
- Mac OSX的c++中的变量类型结构(oaidl.h)
- 嵌套类型:结构与类
- 如何在 python 中实现 c++ 类型结构
- 如何使用类型结构定义双端队列(双面队列)
- 删除类型结构的元素形式向量
- 从类型结构的向量中删除元素
- 在c#、c++和java中创建python弱类型结构的强类型版本
- 从较大的数据类型(结构)转换为较小的数据类型
- 使用QGLShaderProgram从Qt传递自定义类型(结构体)统一到GLSL
- 如何:公开c++数据结构/类型(结构体,枚举)供c#使用
- 按值将类型结构传递给函数,错误:声明"average"中的两个或多个数据类型!!-