我知道类中的纯虚函数会使该类抽象。这意味着我无法使用该类创建对象,并且我必须在所有派生类中覆盖该虚函数。
我有以下代码:
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
我该如何解决这个问题?谢谢。
答案 0 :(得分:3)
将参数传递给基类的语法如下:
Dreptunghi::Dreptunghi(double h, double v) : Forma(h, v) {}
您编写它的方式,而是尝试创建Forma
的实例,当然这是不允许的。