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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章