0
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
}

Shape 是父类,square 是子类。两者都有 computeArea();

当代码到达 computeArea() 时,我遇到了一个奇怪的运行失败错误。该程序只是终止而没有给我任何错误让我找到并修复它......它只是显示运行失败并停止程序。

如果代码在 inputdata() 内,则程序能够正常运行并显示 ->computeArea() 但是当我将它分开时,它只是无法正常运行。有什么解决办法吗?

4

3 回答 3

3

这个Square

Square sqr(len,width);

是 . 范围内的一个实例inputdata。离开该范围后,您将在shape[0]. 如果要设置全局sqr,则需要

sqr = Square(len,width);

您应该找到一个不依赖全局变量的解决方案。

于 2013-05-08T13:32:25.777 回答
1

Square sqr(len, width)创建一个自动对象。当函数返回时它会消失,即使它的地址已经存储在shape[0].

于 2013-05-08T13:32:16.433 回答
0

以这种方式更改您的代码:

Shape *shape[100];//global scope
Square *sqr;//global scope  //make it a pointer or reference


void inputdata() {
int len,width;
cout << "enter length";
cin >> len;
cout << "enter width";
cin >> width;
sqr = new Square(len,width);
shape[0] = sqr;   //remove & here
}
void computeArea() {
shape[0]->computeArea(); 
}
于 2013-05-08T13:37:14.120 回答