- 報錯信息一
invalid new-expression of abstract class type
基類純虛函數
virtual double getArea()=0;
然而子類重寫虛函數:
virtual double getArea() const{
return PI*radius*radius;
}
所以報錯原因是純虛函數沒有加const,或者子類虛函數去掉const,兩者須保持一致,否則不可被認定爲重寫虛函數。
- 報錯信息二
cannot declare field "xxx" to be of abstract type"xxx"
報錯原因:把c++抽象類(含純虛函數的類叫抽象類)當做成員對象,因爲抽象類不可實例化,解決方法把實例對象改成指針
參考鏈接:https://stackoverflow.com/questions/4296276/c-cannot-declare-field-to-be-of-abstract-type
錯誤代碼:
#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;
}