您能否详细说明为什么此代码在上述位置崩溃?我对此有些困惑。我猜想它与sizeof(int)
有关,但是我不确定。有人可以解释吗?
class Base
{
public:
virtual void SomeFunction()
{
printf("test base\n");
}
int m_j;
};
class Derived : public Base {
public:
void SomeFunction()
{
printf("test derive\n");
}
private:
int m_i;
};
void MyWonderfulCode(Base baseArray[])
{
baseArray[0].SomeFunction(); //Works fine
baseArray[1].SomeFunction(); //Crashes because of invalid vfptr
baseArray[2].SomeFunction(); //Crashes because of invalid vfptr
baseArray[3].SomeFunction(); //Works fine
baseArray[4].SomeFunction(); //Crashes because of invalid vfptr
baseArray[5].SomeFunction(); //Crashes because of invalid vfptr
baseArray[6].SomeFunction(); //Works fine
baseArray[7].SomeFunction(); //Crashes because of invalid vfptr
baseArray[8].SomeFunction(); //Crashes because of invalid vfptr
baseArray[9].SomeFunction(); //Works fine
}
int _tmain(int argc, TCHAR* argv[])
{
Derived derivedArray[10];
MyWonderfulCode(derivedArray);
return 0;
}
最佳答案
引用此常见问题解答:Is array of derived same as as array of base?
关于c++ - 为什么此代码在提到的位置崩溃?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1043402/