关于虚函数,错误
About Virtual function, errors
我想创建一个形状类,在xy和区域外绘制矩形和圆形。我必须使用虚函数,它会出现错误:
43 10 D:CppTurboC4OOPCpp Shape . Cpp[错误]无法将字段Circle::r声明为抽象类型ShapeD:CppTurboC4OOPCpp Shape . Cpp,因为以下虚拟函数在"Shape"中是纯的:18 18 D:CppTurboC4OOPCpp Shape . Cpp virtual float 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();
}
当您在Circle
中声明成员变量r
时,则声明Shape
类的实例。由于Shape
是一个抽象类,这是不可能的。
您需要将变量r
设置为引用或指针。
在进一步阅读代码之后,您可能根本不应该在这里使用成员变量,而应该使用从
Shape
基类继承的x
和y
成员。就像你在Rectangle
课上做的那样
问题就在这里:
class Circle: public Shape{
protected:
Shape r; // Wrong
因为Shape是一个纯虚函数,所以不能创建它的实例(这正是Shape r
试图做的)。
可能的解决方案:
class Circle: public Shape{
protected:
int x, y
...
public Circle() {
x = y = 0; // Do you really need "r" at all? Why not just x and y?
...
也:
如果你真的在使用Turbo c++…请不要。它已经过时20年了……这很重要。尤其是当你在学习的时候。有很多免费和/或开源的c++编译器可能会更好地为您服务…
相关文章:
- 链接器错误:函数的多个定义
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:函数声明符之后的预期函数体
- C 错误 - 函数不能超载
- 如何修复传递参数时调用错误函数的主函数?(C++)
- 错误:函数调用中有两个参数
- 错误:函数不是“类”的静态数据成员 - C++
- C ,G 编译错误函数
- CMake 解析错误函数缺少结尾")"。而是找到带有文本的未终止字符串")
- C++ 错误 函数 2 的多重定义
- 错误:函数调用中从int到int(*)[4]的转换无效
- C++14 自动扣除错误:函数返回一个数组
- 视觉C++错误:函数必须返回一个值
- 错误:函数声明中的两种或多种数据类型
- 错误:函数未在作用域中声明
- rtw_android.c错误:函数“strnicmp”的隐式声明[-Weror=隐式函数声明]
- 错误:函数中的return语句没有值,返回“void*”[-fpermission]
- 简单程序中的链接器错误:函数的多重定义
- 错误:函数参数太多
- 错误:函数__tmaincrtstartup中引用的未解析的外部符号_main