【问题标题】:object inheritance virtual function run fail error对象继承虚函数运行失败错误
【发布时间】:2013-05-02 18:21:44
【问题描述】:
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() 但是当我将它分开时,它只是无法正常运行。有什么解决办法吗?

【问题讨论】:

  • 从你发布的代码来看,我看不出问题,你可能在其他地方有问题。

标签: c++ object inheritance polymorphism virtual


【解决方案1】:

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

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

【讨论】:

  • 不需要这种动态分配。
  • @juanchopanza 动态分配有什么问题?
  • 不需要它,为什么要使用它呢?现在您有了一个需要跟踪和删除的资源。
  • @juanchopanza 好的,知道了。 跟踪并删除它让我信服。
【解决方案2】:

这个Square

Square sqr(len,width);

inputdata 范围内的本地实例。一旦你离开这个范围,你就会在shape[0] 中留下一个悬空指针。如果要设置全局sqr,则需要

sqr = Square(len,width);

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多