2016-09-26 64 views
2

假設我們有一個基類和一個派生類:快速基礎對象的所有成員分配給派生對象在C++

class Base { 
    string s1; 
    string s2; 
    ... 
    string s100; // Hundreds of members 
}; 

class Derived : public Base{ 
    string s101; 
}; 

欲基礎對象base分配給一個派生對象derived。我知道我們不能只用運算符「=」來爲它的派生對象分配一個基礎對象。 我的問題是:我們是否必須逐一製作所有成員的副本?像:

derived.s1 = base.s1; 
derived.s2 = base.s2; 
... 
derived.s100 = base.s100; 

有沒有更快或更簡潔的方法來做到這一點?過載操作符= 返回的基礎對象?

+1

基地=衍生? – Danh

+0

派生對象不在那裏,我當時只有一個基礎對象作爲數據源。我想創建一個新的派生對象,分配它的成員並將其放入一個容器中,比如地圖。 –

+1

那你爲什麼寫'base.s1 = derived.s1' – Danh

回答

2

I want to assign a Base object base to a Derived object derived.

提供過載operator=它:

class Derived : public Base { 
    Derived& operator=(const Base& b) { 
     Base::operator=(b); // call operator= of Base 
     s101 = something; // set sth to s101 if necessary 
     return *this; 
    } 
}; 

然後你就可以

Base b; 
// ... 
Derived d; 
// ... 
d = b; 
2

I know we can't just use operator "=" to assign a base object to its derived object.

當然,你可以(在這個問題的背景下):

static_cast<Base &>(derived)=base; 

股票例如:

class Base {}; 

class Derived : public Base {}; 

void foo() 
{ 
    Derived d; 
    Base b; 

    static_cast<Base &>(d)=b; 
} 
+0

謝謝,我會試試這個static_cast。然而,即使在這種情況下,這是一個很好的做法嗎? –

+0

@ M.M - 不符合gcc 6.1.1:「t.C:12:4:錯誤:不匹配'operator ='(操作數類型是'Derived'和'Base')」 –

+0

@SamVarshavchik不夠公平 –

0

I know we can't just use operator "=" to assign a base object to its derived object

這不是真的。

Do we have to make copies of all the members one by one? Like: base.s1 = derived.s1; base.s2 = derived.s2; ... base.s100 = derived.s100;

不是。正如Danh在第一條評論中提到的那樣。

base = derived 

就足夠了,因爲它執行隱式動態上傳(即從指針到派生到指針到基址的轉換)。見http://www.cplusplus.com/doc/tutorial/typecasting/

相關問題