问题描述
- 关于c++抽象类的问题,调用虚函数
- #include
#include
using namespace std;
class shape
{
public:
virtual float area() const=0;
};
class circle:public shape
{
public:
circle(float r)
{
radius=r;
}
virtual float area() const
{
return 3.14159*radius*radius;
}
protected:
float radius;
};
class rectangle:public circle
{
public:
rectangle(float rfloat lfloat wfloat h):circle(r)
{
length=l;
width=w;
height=h;
}
virtual float area()
{
return length*width*height;
}
protected:
float length;
float width;
float height;
};
class triangle:public rectangle
{
public:
triangle(float rfloat lfloat wfloat hfloat a1float b1float c1):rectangle(lwhr)
{
a=a1;
b=b1;
c=c1;
}
virtual float area() const
{return sqrt(((a+b+c)/2)*(((a+b+c)/2)-a)*(((a+b+c)/2)-b)*(((a+b+c)/2)-c));}
protected:
float a;
float b;
float c;
};
int main()
{
circle c(2);
rectangle re(1111);
triangle t(2445345);
circle *p=&c;
cout<area()< p=&re;
coutarea()< p=&t;
coutarea()<<endl;return 0;
}
程序可以运行 但是对象c和对象re调用的display()函数为什么是同一个 ?求大神帮助啊
解决方案
rectangle 的 area 方法缺了const所以不认为是基类的area的重写
时间: 2024-12-01 06:19:44