2013-05-08 47 views
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()我有一个奇怪的运行失败错误。该程序只是终止,没有给我任何错误,我找到并修复它......它只是显示运行失败并停止程序。

该程序能够正常运行,并显示 - > computeArea()如果代码是在inputdata()内,但是当我分开它时,它只是无法正常运行。任何解决方案?

+0

从您发布的代码,我没有看到一个问题,你可能有错误的东西在其他地方。 – 2013-05-08 13:32:05

回答

3

Square

Square sqr(len,width); 

是一个实例,其是本地的inputdata范围。一旦你离开这个范围,你将留下一个悬挂指针shape[0]。如果你想设置全局sqr,你需要

sqr = Square(len,width); 

你应该找到一种不依赖于全局变量,虽然一个解决方案。

+0

好吧,现在的作品非常感谢! – user2351750 2013-05-08 13:51:53

1

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

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(); 
} 
+0

没有必要进行这种动态分配。 – juanchopanza 2013-05-08 13:38:57

+0

@juanchopanza动态分配有什么问题? – 2013-05-08 13:43:55

+0

没有必要,为什么要使用它?现在你有一个资源需要跟踪和删除。 – juanchopanza 2013-05-08 13:46:30