【问题标题】:Assigning one structure type into another type in c++在 C++ 中将一种结构类型分配给另一种类型
【发布时间】:2018-01-15 10:29:01
【问题描述】:

我们知道我们只能将一个结构对象分配给另一个具有相同类型的结构对象,但是为什么我们不能将一个 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 结构的对象,因为它们的成员类型相同?

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

【问题讨论】:

  • "为什么不将不同类型的结构对象分配给另一个,因为它们可能具有相同的成员?" 您假设此行为将是默认行为,必须有一个规则来停止它的工作。实际上,必须有一个规则允许它工作。不同的类型是不同的,即使你认为它们是相同的。

标签: c++ object memory structure


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

    varA = (typeA)varB;
    

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

    【讨论】:

    • 由于这个问题是关于 C++ 的,您是否愿意将演员表更改为 reinterpret_cast 并警告 OP 它的潜在陷阱?谢谢。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 2020-12-30
      • 2018-06-04
      • 1970-01-01
      • 2011-05-26
      • 2021-04-11
      • 2023-02-07
      • 1970-01-01
      相关资源
      最近更新 更多