• 报错信息一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;
}

更多推荐