class Base1
{
private:
int testInput;
public:
Base1();
virtual int GetRow(void) = 0;
};
Base1::Base1()
{
testInput = 0;
}
class table : public Base1
{
private:
int row;
public:
table();
virtual int GetRow(void);
};
table::table()
{
//Contructor
row = 5;
}
int table::GetRow()
{
return row;
}
int main()
{
Base1* pBase = new table[3];
pBase[0].GetRow();
pBase[1].GetRow(); //when i get to this line, the compiler keep saying access
// violation.
pBase[2].GetRow();
return 0;
}
我想創建一個3表類的數組。要求是我必須使用Base對象來做到這一點。如何在C++中創建一個具有多態性的數組?
Base1 * pBase = new table[3];
看起來不錯。但是當我試圖訪問每個表時,編譯器說它是訪問衝突。我不知道這段代碼有什麼問題。雖然我使用Visual Studio 2010。
and shhh ..但鑄造到正確的類型,然後調用鑄造類型的方法將防止崩潰 – johnathon
你的意思是'((table)pBase)[1] .GetRow()'?這將會起作用,但這是一件可怕的事情,幾乎肯定會回來並咬你。 –
是的,我確實是這個意思。是的,它非常「可怕」,但它是哄騙編譯器訪問正確地址處的多態對象的一種非常有效的方式。 – johnathon