簡體   English   中英

將結構的一部分分配給c中的另一個結構

[英]assign parts of struct to another struct in c

我想要在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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM