在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;
}

为什么我们不能将typeB结构的对象分配给typeA结构的对象,因为它们具有相同类型的成员?

为什么规定不能将不同类型的结构对象分配给另一个,因为它们可能具有相同的成员?

为了安全起见,您不能将不同的类型分配给彼此。虽然底层类型在字面上是兼容的,但编译器不知道语义 - 您可能不小心将某人的年龄和体重分配给了他们的血压测量值。

如果您真的确定要这样做,可以将 varB 转换为 typeA:

varA = (typeA)varB;

这告诉编译器你非常确定你想要做什么,虽然在某些情况下,如果编译器检测到你可能丢失了一些正在携带的信息,它可能会选择警告你仍然,但是它也可能不会。

编译器会生成一个赋值运算符来给同类型的变量赋值。但是,即使两种类型具有相同的布局,它也不会为其生成赋值运算符。这也是完全可以理解的,因为它很容易出错。

为什么它会成为错误来源?

好吧,想象一下如果 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;
    }
};

现在编译器知道如何按照您想要的方式分配它们。

这不是您正在寻找的确切答案,但如果您不想要显式构造函数。您可以让 隐式构造函数 处理这种情况 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;
}