2017-10-20 96 views
1

我不知道是否有人解決了以下問題,我有兩個幾乎相同的結構,我需要將結構A中的值傳遞給結構B,並且它們有一個成員的差異。在幾乎相同的結構之間傳遞成員值

例子看起來是這樣的,我有以下結構:

struct insideA 
{ 
double C1; 
double C2; 
int C3; 
str C4; 
}; 

struct insideB 
{ 
int D3; 
str D4; 
}; 

struct A 
{ 
insideA inA; 
double c; 
std::string d; 
} a; 

struct B 
{ 
insideB inB; 
double c; 
std::string d; 
} b; 

既然結構A和B都幾乎相似,但並不完全相同,如果我們想象的B填充,我可以很容易地通過會員從動地重視成員:

a.inA.C3 = b.inB.D3; 
a.inA.C4 = b.inB.D4; 
a.c = b.c; 
a.d = b.d; 

而且現在有所有b的,我可以填充的其他成員的信息。所以我的問題是,我必須用不同的結構執行大約30或40次,只有結構的第一個成員發生變化,那麼是否有更好的方法來完成此工作,而不是將值的struct成員傳遞給struct成員b單獨嗎?

+0

使一個基類包含相同的成員並實現複製。 「幾乎相同」不會幫你太多 – user463035818

+1

你可以修改現有的結構定義嗎? – nate

+0

不,我不能編輯現有的結構,因爲它是在驅動程序中,我無法訪問源代碼:( – Pedro

回答

1

讓我們使用模板!

template <struct Inside> 
struct AorB 
{ 
    Inside in; 
    double c; 
    std::string d; 

    template <struct OtherInside> 
    AorB& operator=(const AorB<OtherInside>& that) { 
    in = that.in; 
    c = that.c; 
    d = that.d; 
    } 
}; 

struct A : AorB<insideA> 
{ 
    template <struct OtherInside> 
    A& operator=(const AorB<OtherInside>& that) { 
    AorB<insideA>::operator=(that); 
    return *this; 
    } 
}; 

struct B : AorB<insideB> 
{ 
    template <struct OtherInside> 
    B& operator=(const AorB<OtherInside>& that) { 
    AorB<insideB>::operator=(that); 
    return *this; 
    } 
}; 

您可以將此想法擴展到內部類。

+0

嘿, 感謝您的快速回復,我試圖仔細描述我的問題,但我忘了澄清我必須通過的所有不同的結構之間,他們每個人的「身體」成員是不同的,所以用這種方法,我需要確實需要爲他們每個人做一個類似的解決方案,然後看看使用哪個模板在這種情況下,我想如果有辦法以某種方式實現自動化 – Pedro

相關問題