我一直在嘗試重寫我的程序以允許繼承類。我遇到了切片問題。我原本在我的Test
類中有Parent m_parent
(因此在Test中沒有動態分配),但補充說,認爲它會解決我的問題,但它沒有。我不知道我是否會讓我的問題變得更糟,或者如果寫作複製構造函數(或其他簡單修復)那麼簡單。在方法調用中避免對象切片
class Parent
{
public:
Parent();
private:
string a;
};
class Child : public Parent
{
private:
string b;
};
class Test
{
public:
Test()
{
m_parent = new Parent;
}
void testFunction(Parent &parent)
{
*m_parent = parent;
}
~Test()
{
delete m_parent;
}
private:
Parent * m_parent;
};
做這樣的事情還是引起了切片...
Child c("foo", "bar");
Parent * p = &c;
Test.testFunction(*p);
所以要複製母公司的任意派生的實例? – Shaggi
提醒我一個[老問題](http://stackoverflow.com/questions/23220589/code-selector-using-inheritage-during-runtime)我有。自從我使用智能指針。使用[C++ 11](http://www.codeproject.com/Articles/541067/Cplusplus-Smart-Pointers)或[boost](http://www.codeproject.com/Articles/8394/Smart-Pointers -to-升壓你的代碼)。 – William