在 c++ 中将一种结构类型分配给另一种类型

Assigning one structure type into another type in c++

本文关键字:类型 结构 一种 分配 另一种 c++      更新时间:2023-10-16

我们知道我们只能将一个结构对象分配给另一个具有相同类型的结构对象,但为什么我们不能将一个类型为 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具有相同的布局,您也期望inA1inB1的值,但相反的情况会发生,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;
}