/*copyright(c)2016.烟台大学计算机学院
* All rights reserved,
* 文件名称:text.Cpp
* 作者:刘涛
* 完成日期:2016年5月7日
* 版本号:vc++6.0
* 问题描述:建立一个点类
*/
#include<iostream>
using namespace std;
#define Pi 3.1415926
class Point
{
private:
double x,y;
public:
Point(double x1,double y1):x(x1),y(y1){}
double getX()
{
return x;
}
double getY()
{
return y;
}
void print()
{
cout<<"横坐标:"<<x<<" "<<"纵坐标:"<<y<<endl;
}
};
class Circle:public Point
{
private:
double r;
double area;
double perimeter;
public:
Circle(double x1,double y1,double r1):Point(x1,y1),r(r1){}
void Area()
{
area=Pi*r*r;
}
void Perimeter()
{
perimeter=2*Pi*r;
}
void showRadius()
{
cout<<"该圆半径为:"<<r<<endl;
}
void showArea()
{
cout<<"该圆面积为:"<<area<<endl;
}
void showPerimeter()
{
cout<<"该圆周长为:"<<perimeter<<endl;
}
double getArea()
{
return Pi*r*r;
}
double getPerimeter()
{
return 2*Pi*r;
}
};
class Cylinder:public Circle
{
private:
double h;//圆柱的高
double area1;//圆柱的面积
double volume;//圆柱的体积
public:
Cylinder(double x1,double y1,double r1,double h1):Circle(x1,y1,r1),h(h1){}
void CalArea1()
{
area1=Circle::getArea()*2.0+Circle::getPerimeter()*h;
}
void CalVolume()
{
volume=Circle::getArea()*h;
}
void printh()
{
cout<<"圆柱高为:"<<h<<endl;
}
void printArea1()
{
cout<<"圆柱表面积为:"<<area1<<endl;
}
void printVolume()
{
cout<<"圆柱体积为:"<<volume<<endl;
}
};
int main()
{
Point p(2.0,3.0);
p.print();
Circle c(2.0,3.0,2.0);
c.Area();
c.Perimeter();
c.showRadius();
c.showArea();
c.showPerimeter();
Cylinder cc(2.0,3.0,2.0,4.0);
cc.CalArea1();
cc.CalVolume();
cc.printh();
cc.printArea1();
cc.printVolume();
return 0;
}
运行结果:
知识点总结:派生和继承。
学习心得:在派生和继承中,要时刻保持清醒,那个类与哪个类什么关系要时刻清楚,当有虚基类的时候要更加小心。
此题中,Cylinder是Circle的派生,Circle是Point的派生类,在Cylinder中的构造函数中,要注意构造的顺序和方式,由于第一次构造成了Point(x1,y1),Circle(r1)发生了错误。