我們假設我有一個名爲BaseClass
的基類和一個從BaseClass
繼承的名爲Foo
的對象。我可以將一個BaseClass
實例的所有成員複製到正在創建的當前對象,而不是手動執行它嗎?將一個類的所有成員複製到當前對象
class BaseClass
{
int a;
int b;
int c;
const char *e;
};
class Foo : BaseClass
{
public:
Foo(BaseClass* bc, int x, const char *value)
{
// copy bc->a to this->a and bc->b to this->b
// and so on with all the members of BaseClass class
this->x = x;
this->s = value;
}
int x;
const char *s;
};
我可以這樣做嗎? 與memcpy()
另一種可能的解決方案,不知道這是否是醜陋的或不能工作,但假設爲了分配的成員,BaseClass
第一,即該類成爲類似內存:在
struct
{
// members of BaseClass
int a;
int b;
int c;
const char *e;
// members of Foo
int x;
const char *s;
};
像這樣的東西Foo
構造:
memcpy(this, &bc, sizeof(*bc));
應的bc
所有成員複製到當前對象,對不對?這是危險嗎?
順便說一句,我正在做一個C風格的。我沒有做太多的C++。 C++ - 做這件事的方式非常受歡迎。
注意對象的切片。複製和多態並不總是很好玩,因爲調用哪個拷貝構造函數是在編譯時確定的。一個常見的解決方案是創建一個虛擬克隆方法,每個派生類根據需要覆蓋返回正確類型的對象。 –