c++报错invalid new-expression of abstract class type和cannot declare field "" to be of abstract type""

  • 报错信息一invalid new-expression of abstract class type
    基类纯虚函数
virtual double getArea()=0;

然而子类重写虚函数:

virtual double getArea() const{
        return PI*radius*radius;
    }

所以报错原因是纯虚函数没有加const,或者子类虚函数去掉const,两者须保持一致,否则不可被认定为重写虚函数。

错误代码:

#include<iostream>

#define PI 3.1415926
using namespace std;

class Geometry {
public:
    virtual double getArea() const = 0;
};

class Circle : public Geometry{
public:
    Circle(double rad):radius(rad){}
    virtual double getArea() const{
        return PI*radius*radius;
    }
private:
    double radius;
};

class Pillar{
public:
    double getVolume(){
        return bottom.getArea()*height;
    }
private:
    Geometry bottom; //错误处, 改为Geometry *bottom;
    double height;
};

关键点:

 Geometry bottom; //错误处
 Geometry *bottom;//正确

完整正确及测试代码:

#include<iostream>

#define PI 3.1415926
using namespace std;

class Geometry {
public:
    virtual double getArea() const = 0;
};

class Circle : public Geometry{
public:
    Circle(double rad):radius(rad){}
    ~Circle(){}
    virtual double getArea() const{
        return PI*radius*radius;
    }
    double getRadius() const{
        return radius;
    }
private:
    double radius;
};

class Rectangle : public Geometry{
public:
    Rectangle(double len,double wid):length(len),width(wid){}
    ~Rectangle(){}
    virtual double getArea() const{
        return length*width;
    }
    double getLength() const{
        return length;
    }
    double getWidth() const{
        return width;
    }
private:
    double length;
    double width;
};
class Pillar{
public:
    double getVolume(){
        return bottom->getArea()*height;
    }
	Pillar(Geometry*geometry,double height):bottom(geometry),height(height){}
	void setButtom(Geometry*geometry){
		this->bottom = geometry;
	}
	void setHeight(double height){
		this->height = height;
	}
	double getHeight(){
		return height;
	}
	double getArea() const{
		return bottom->getArea();
	}
private:
    Geometry* bottom;
    double height;
};
int main(){
	int height = 5;
    Geometry* geometry = new Rectangle(3.0,4.0);
	Pillar pillar(geometry,height);
    cout<<"长方体面积是"<<pillar.getVolume()<<endl;
	geometry = new Circle(3.0);
    pillar.setButtom(geometry);
    cout<<"圆柱面积是"<<pillar.getVolume()<<endl;
    return 0;
}
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值