【发布时间】:2016-09-12 07:30:39
【问题描述】:
我想创建一个形状类来在 Oxy 中和区域外绘制矩形和圆形。 我必须使用虚函数,它会出错:
43 10 D:\Cpp\TurboC4\OOPCpp\shape.cpp [错误] 不能将字段 'Circle::r' 声明为抽象类型 'Shape' 6 7 D:\Cpp\TurboC4\OOPCpp\shape.cpp 因为以下虚函数在“Shape”中是纯函数: 18 18 D:\Cpp\TurboC4\OOPCpp\shape.cpp 虚拟浮点数 Shape::area()
这是我的代码:
class Shape{
public:
int x,y;
public:
void set_data (int a,int b){
x=a;
y=b;
}
void input(){
cout<<"x= "; cin>>x;
cout<<"y= "; cin>>y;
}
virtual float area()=0;
};
class Rectangle: public Shape{
public:
Rectangle(){
x=0;
y=0;
}
Rectangle(int x,int y){
this->x=x;
this->y=y;
}
void input(){
cout<<"Enter value of width and height: ";
cin>>x;
cin>>y;
}
float area(){
return x*y;
}
};
class Circle: public Shape{
protected:
Shape r;
public:
Circle(){
r.x=0;
r.y=0;
}
//center of Circle: default(0,0) , r is 1 point in the circle.
Circle(int x,int y){
r.x=x;
r.y=y;
}
void nhap(){
cout<<"Enter values x,y of r: ";
cin>>x;
cin>>y;
}
virtual float area(){
float a=sqrt(r.x*r.x+r.y*r.y);
return 3.14*a*a;
}
};
class ArrayOfShape{
private:
int n;
Shape **a;
public:
void nhap(){
int hinh;
cout<<"input number of shape: ";
cin>>n;
a=new Shape*[n];
for (int i=0;i<n;i++){
cout<<"\nEnter shape (1:rectangle,2:circle): ";
cin>>hinh;
if (hinh==1){
Rectangle *p=new Rectangle();
p->nhap();
a[i]=p;
}
else{
if(hinh==2){
Circle *e=new Circle();
e->input();
a[i]=e;
}
else{
cout<<"Invilid input";
}
}
}
}
void area(){
for (int i=0;i<n;i++)
cout<<"\nArea of shape"<<i+1<<" : "<<a[i]->area();
}
};
int main(){
ArrayOfShape a;
a.input();
a.area();
}
【问题讨论】:
-
C++ 中不允许使用对象抽象类。
-
您的问题是当您尝试添加
Circle的受保护成员时,如Shape r。这不可能,因为Shape是抽象类。 -
Shape 是一个抽象类,您尝试在 Circle 类中创建抽象类对象。
-
我希望
r是圆的半径,而不是Shape。 -
感谢您的帮助!明白了
标签: c++