Shape *shape[100];//global scope
Square sqr;//global scope
void inputdata() {
int len,width;
cout << "enter length";
cin >> len;
cout << "enter width";
cin >> width;
Square sqr(len,width);
shape[0] = &sqr;
//----> if shape[0]->computeArea(); here works fine.
}
void computeArea() {
shape[0]->computeArea(); // --> run fail error
}
形状是父类,正方形是子类。都具有computeArea();
当代码到达computeArea()时,我遇到了一个奇怪的运行失败错误。该程序只是终止而没有给我任何错误供我查找和修复它...它只是表明运行失败并停止了该程序。
该程序能够正常运行,并且如果代码在inputdata()内,则显示-> computeArea(),但是当我将其分离时,它只是无法正常运行。有什么解决办法吗?
最佳答案
此Square
Square sqr(len,width);
是在
inputdata
范围内本地的实例。离开该范围后,在shape[0]
中将剩下一个悬空的指针。如果要设置全局sqr
,则需要sqr = Square(len,width);
您应该找到一个不依赖全局变量的解决方案。
关于c++ - 对象继承虚拟函数运行失败错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16442058/