【问题标题】:virtual function in base class基类中的虚函数
【发布时间】:2014-02-21 19:42:21
【问题描述】:

假设我有一个形状基类 shape 和两个派生类 squarecircle。 现在我想要一个没有指定形状的函数

double foo(shape S)
{
return getArea;
}

但是调用时会打印正方形的面积

square sq();
foo(sq);

和调用时圆的面积

circle cr();
foo(cr);

因此,我在基类中声明了一个虚函数(仅返回 0),并在两个派生类中声明了相应的虚函数。 但是,当使用方形或圆形对象调用 foo 时,我总是得到基类的结果。如何正确地做到这一点?


编辑:

现在代码可以工作了,这里是一个简单的例子。解决方案确实是通过 referenceshape 类(派生或非派生)中传递对象。这允许定义一个接受所有类型派生对象的通用函数:

#include<iostream>

using namespace std;


class shape
{
public:
  shape (double L_par): L(L_par){};
  double getL(){return L;}
  virtual double getArea(){return 0;}

private:
    const double L;
}; 
class square: public shape
{
public:
  square (double L_par): shape(L_par),area(L_par*L_par){cout<<"square with area="<<area<<endl;};
   virtual double getArea(){return area;}

private:
    const double area;
};
class circle: public shape
{
public:
  circle (double L_par): shape(L_par),area(3.1415*L_par*L_par){cout<<"circle with area="<<area<<endl;};
  virtual double getArea(){return area;}

private:
const double area;
};

void foo(shape &shp)
{
  cout<<"L="<<shp.getL()<<endl;
  cout<<"area="<<shp.getArea()<<endl;
}

int main(int argc, char* argv[])
{
  double L=4;
  square sq1(L);
  circle cr1(L);

  foo(sq1);
  foo(cr1);
  cout<<sq1.getArea()<<endl;
  cout<<cr1.getArea()<<endl;
  return 0;
}

【问题讨论】:

  • 请发布您的所有代码...
  • 我猜你是object-slicing 的受害者,从你发布的示例代码中无法确定。

标签: c++ virtual-functions derived-class


【解决方案1】:

您正在通过值传递shape

double foo(shape S) { .... }

这意味着函数只有对象的shape 部分的副本。这称为object slicing。您可以通过传递参考来解决此问题:

double foo(const shape& S) { .... }

【讨论】:

    【解决方案2】:

    通过 C++ 的动态绑定是使用引用和指针实现的。因此,您的函数foo 应该引用形状;

    double foo(shape &s) {
        return s.getArea(); //your virtual function?
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 2010-10-17
      • 2020-09-30
      • 2014-08-16
      相关资源
      最近更新 更多