2011-10-18 40 views
0

我該怎麼做?我想到了複雜類中的一種方法,它將基本對象的每個變量都複製到複雜對象上,但這似乎有點不方便。將基礎類的對象擴展爲複雜類的對象

class Basic 
{ 
    //basic stuff 
} 

class Complex : public Basic 
{ 
    //more stuff 
} 

Basic * basicObject = new Basic(); 
//now "extending" basicObject and "cast" it to Complex type 
//which means copy everything in basicObject to an complexObject 

或類似的東西:

Complex * complexObject = new Complex(); 
complexObject.getEverythingFrom(basicObject); 

似乎是太不方便了,因爲每次我改變基本類,我必須得改變這種「複製」的方法。

+0

我不認爲你問的東西有很大的意義。也許更好地陳述你的目標,而不是你決定成爲第一步。 –

+0

你應該多讀一點繼承以及它是如何工作的。 –

+0

你不能這樣做。當你創建一個'Basic'對象時,你不能強制轉換爲派生的'Complex'。此外,每個派生類都將自己的基類變量作爲自己的變量。爲什麼你需要執行這個副本,如果你可以直接訪問所有的基礎變量? –

回答

1

定義要在保護部分的類之間共享像這樣的價值觀:

class Base 
{ 
public: 
int myPublicShared1; 
int myPublicShared2; 

Base& operator = (Base& other) 
{ 
    // Copy contents in base across 
    return *this; 
} 
protected: 
int myShared1; 
int myShared2; 

private: 
int notShared1; 
int notShared2; 
}; 

class Derived : public Base 
{ 
public: 
Derived& operator = (Derived& other) 
{ 
    Base::operator = (other); 
    // copy the rest of variables specific to Derived class. 
} 
Derived& operator = (Base& other) 
{ 
    Base::operator = (other); 
} 
// Derived now has all variables declared in Base's public and protected section 
}; 
+0

謝謝。這看起來相當不錯,但不幸的是我的Base類沒有=運算符,但我將其標記爲解決方案,因爲它似乎是最方便的解決方案。 – ben

+0

@ben:我添加了賦值操作符來表明它必須被添加。你可以使用'(* complexObject)= * baseObject'。或者你甚至可以將該函數重命名爲'Base :: assign(const Base *)'和'Derived :: assign(const Base *); Derived :: assign(const Derived *)'。然後你可以像這樣使用它:'complexObject-> assign(baseObject);':)。 –

0

在C++中,對象不能改變它們的類型。

所以,要麼你重寫你的程序馬上創建Complex對象,或者您創建一個副本構造函數,這樣就可以做到:

新大樓(* basicObject);

附註:從擴展和新的使用看來,你似乎來自一個Java世界。不要認爲你在java中做事情的方式也是你在C++中如何做的錯誤。

+0

好吧,這就像我的複製方法的想法,只是在構造函數,對不對? – ben

+0

@ben:複製ctor是使用C++中的對象時的一個基本元素,你應該讀一下它。 – PlasmaHH