【问题标题】:Virtual pure functions虚纯函数
【发布时间】:2014-05-25 06:30:49
【问题描述】:

我知道类中的纯虚函数使该类抽象。这意味着我无法使用该类创建对象,并且必须在所有派生类中覆盖该虚函数。

我有以下代码:

class Forma{
    protected:
        double x,y;
    public:
        Forma(double h=0, double v=0);
        virtual double Arie() const;
        virtual double Perimetru() const=0;
};

class Dreptunghi: public Forma{
    public:
        Dreptunghi(double h=0, double v=0);
        virtual double Arie() const;
        virtual double Perimetru() const;
};

class Cerc:public Forma{
    protected:
        double raza;
    public:
        Cerc(double h=0, double v=0, double r=0);
        virtual double Arie() const;
        virtual double Perimetru() const;
 };

 Forma::Forma(double h,double v){x=h; y=v;}
 double Forma::Arie() const{return x*y;}
 double Forma::Perimetru() const{return x+y;}

 Dreptunghi::Dreptunghi(double h,double v){Forma(h,v);}
 double Dreptunghi::Arie() const{return x*y;}
 double Dreptunghi::Perimetru() const{return 2*x+2*y;}

我的错误如下:

33 53 [Error] cannot allocate an object of abstract type 'Forma'
4 7   [Note] because the following virtual functions are pure within 'Forma':
31 9  [Note] virtual double Forma::Perimetru() const

我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: c++ inheritance overriding virtual pure-virtual


    【解决方案1】:

    将参数传递给基类的语法如下:

    Dreptunghi::Dreptunghi(double h, double v) : Forma(h, v) {}
    

    按照您的编写方式,它会尝试创建Forma 的实例,这当然是不允许的。

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2020-12-13
      • 2011-08-06
      • 2016-03-07
      • 2022-01-13
      相关资源
      最近更新 更多