📄 p410 例12.4 虚函数和虚基类的应用.cpp
字号:
#include<iostream>
using namespace std;
class Shape
{
public:
Shape(){}
virtual float area()const {return 0;}
virtual float volume()const {return 0;}
virtual void showname()const=0;
virtual void display() const =0;
};
class Point:public Shape
{
private:
float x,y;
public:
Point(float a=0,float b=0):x(a),y(b){}
void showname() const{ cout<<"the information of a point: ";}
void display()const;
};
void Point::display()const
{
cout<<"x="<<x<<" y="<<y<<endl;
}
class Circle:public Point
{
protected:
float r;
public:
Circle(float a,float b,float c):Point(a,b),r(c){}
float area()const;
void showname()const { cout<<"the information of the circle :"; }
void display()const;
};
float Circle::area()const
{
return 3.1415*r*r;
}
void Circle::display() const
{
Point::display();
cout<<" r="<<r<<endl;
}
class Cylinder:public Circle
{
private:
float height;
public:
Cylinder(float a=0,float b=0,float c=0,float d=0):Circle(a,b,c),height(d){}
float area()const ;
float volume()const ;
void showname()const;
void display() const;
};
float Cylinder::area()const
{
return 2*Circle::area()+2*3.1415*r*height;
}
float Cylinder::volume()const
{
return Circle::area()*height;
}
void Cylinder::showname()const
{
cout<<"the information of the cylinder: ";
}
void Cylinder::display()const
{
Circle::display();
cout<<"the height="<<height<<endl;
}
int main()
{
Point p(23.4,56);
Shape *s=&p;
s->showname();
s->display();
cout<<"the area ="<<s->area()<<endl;
cout<<"the volum ="<<s->volume()<<endl;
Circle c(34,23,4);
s=&c;
s->showname();
s->display();
cout<<"the area ="<<s->area()<<endl;
cout<<"the volum ="<<s->volume()<<endl;
Cylinder cy(23,45,24,12);
s=&cy;
s->showname();
s->display();
cout<<"the area ="<<s->area()<<endl;
cout<<"the volum ="<<s->volume()<<endl;
system("pause");
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -