c++中 抽象类 继承 的编程问题

2025-04-04 03:59:10
推荐回答(3个)
回答1:

#include
#define Pi 3.1415926
class Shape
{
public:
Shape(){}
~Shape(){}
virtual void printShapeName( )=0;
virtual void print( )=0;
virtual double GetArea()=0;
virtual double GetVolume( )=0;
};
class Point:public Shape
{
public:
Point(double x,double y){X=x;Y=y;}
~Point(){}
void printShapeName( );
void print( ){}
double GetArea(){return 0;} //添加
double GetVolume( ){return 0;} //添加
private:
double X,double Y;
};
class Circle:public Point
{
public:
Circle(double x,double y,double r):Point(x,y){radius=r;}
~Circle(){}
double GetArea();
void printShapeName( );
void print( ){}
private:
double radius;
};
class Cylinder:public Circle
{
public:
Cylinder(double x,double y,double a,double b):Circle(x,y,a){radius=a;hight=b;}
void GetCylinder(double a,double b){radius=a;hight=b;}
void printShapeName( );
void print( ){}
double GetVolume();
private:
float radius,hight;
};

double Cylinder::GetVolume()
{
return Pi*radius*radius*hight;
}

double Circle::GetArea()
{
return Pi*radius*radius;
}
void Point::printShapeName()
{
cout<<"这是一个点!"<}
void Circle::printShapeName()
{
cout<<"这是一个园!"<}
void Cylinder::printShapeName()
{
cout<<"这是一个圆柱体!"<}
void fun1(Shape *p)
{
p->printShapeName( );
}
void fun2(Shape *p)
{
cout<GetArea();
}
void fun3(Shape *p)
{
cout<GetVolume();
}
void main()
{
Shape *p1;
Shape *p2;
Shape *p3;
Point P(1,1);
Circle C(1,1,1);
Cylinder CY(1,1,1,1);
p1=&P;
fun1(p1);
p1=&C;
fun1(p1);
p2=&C;
fun2(p2);
p1=&CY;
p3=&CY;
fun1(p1);
fun3(p3);
}

你错误是因为你有两个虚函数没有实现。
抽象类中的虚函数在后面必须给出具体的实现,记住教训啊

回答2:

这个错误就是说 不能实例化Point类..你声明了纯虚函数嘛,所以不能实例化

回答3:

把类似这样的语句
void printShapeName( );
改为:
virtual void printShapeName( ) { }