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对象完成。
Base1 * pBase = new table[3];
在我看来,这段代码没问题。但是当我试图访问每个表格时,编译器却说它有访问违规的问题。虽然我使用的是Visual Studio 2010,但我不知道这段代码错在了哪里。
((table)pBase)[1].GetRow()
吗?这样做虽然可行,但是这是一件非常糟糕的事情,几乎肯定会给你带来麻烦。 - Nik Bougalis((table)pBase)[1].GetRow()
不保证可行 *(即使修复了拼写错误)*。你的意思是dynamic_cast<table*>(pBase)[1].GetRow()
?那样就可以了。 - Nawazdynamic_cast<>
与我展示的C样式转换做了非常不同的事情,其最接近的C++等效形式将是static_cast<table*>(pBase)[1].GetRow()
。这个(已更正的)C样式转换在这种情况下被保证能够正确工作,但正如我所指出的那样,它很糟糕,几乎肯定会让人后悔。” - Nik Bougalis