将结构的一部分分配给c中的另一个结构

assign parts of struct to another struct in c

本文关键字:结构 另一个 分配 一部分      更新时间:2023-10-16

我希望在c/c++中有这样的概念

struct first{
   int a,b,c;
}my1;
struct second{
   int a,b,c;
   int extended;
}my2;

以某种方式能够拥有

my2=my1; 

(意思是只复制相同的部分。保持扩展不变)

我想把它当作来解决

struct second{
     first first_;
     int extended;
 }my2;

并具有

my2.first_ = my1;

但这对我来说有点难看。有更明确的解决方案吗?可能是延伸了一个结构什么的?

类似:

struct second : first
{
    int extended;
    second& operator=(const first& f)
    {
        first::operator=(f); extended = 0; return *this;
    }
};

有点同样丑陋,但这里是:

my1 = *(first*)&my2;

您可以为struct second:重载=运算符

second & operator=(const first & s) {
    this->a = s.a;
    this->b = s.b;
    this->c = s.c;
    return *this;
}
相关文章: