博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
子类对象赋值给父类引用
阅读量:5086 次
发布时间:2019-06-13

本文共 2324 字,大约阅读时间需要 7 分钟。

#include <iostream>

using namespace std;
class Point
{
public:
 Point(float=0,float=0);
 void setPoint(float,float);
 float getX() const {return x;}
 float getY() const {return y;}
 friend ostream & operator<<(ostream &,const Point &);
protected:
 float x,y;
};

Point::Point(float a,float b)

{x=a;y=b;}
void Point::setPoint(float a,float b)
{x=a;y=b;}
ostream & operator<<(ostream &output,const Point &p)
{output<<"["<<p.x<<","<<p.y<<"]"<<endl;
return output;
}

class Circle:public Point

{public:
Circle(float x=0,float y=0,float r=0);
void setRadius(float);
float getRadius() const;
float area () const;
friend ostream &operator<<(ostream &,const Circle &);
protected:
 float radius;
};

Circle::Circle(float a,float b,float r):Point(a,b),radius(r){}

void Circle::setRadius(float r)

{radius=r;}

float Circle::getRadius() const {return radius;}

float Circle::area() const

{return 3.14159*radius*radius;}

ostream &operator<<(ostream &output,const Circle &c)

{output<<"Center=["<<c.x<<","<<c.y<<"], r="<<c.radius<<", area="<<c.area()<<endl;
return output;
}

class Cylinder:public Circle

{public:
Cylinder (float x=0,float y=0,float r=0,float h=0);
void setHeight(float);
float getHeight() const;
float area() const;
float volume() const;
friend ostream& operator<<(ostream&,const Cylinder&);
protected:
 float height;
};

Cylinder::Cylinder(float a,float b,float r,float h)

:Circle(a,b,r),height(h){}

void Cylinder::setHeight(float h){height=h;}

float Cylinder::getHeight() const {return height;}

float Cylinder::area() const

{ return 2*Circle::area()+2*3.14159*radius*height;}

float Cylinder::volume() const

{return Circle::area()*height;}

ostream &operator<<(ostream &output,const Cylinder& cy)

{output<<"Center=["<<cy.x<<","<<cy.y<<"], r="<<cy.radius<<", h="<<cy.height
<<"\narea="<<cy.area()<<", volume="<<cy.volume()<<endl;
return output;
}

int main()

{Cylinder cy1(3.5,6.4,5.2,10);
cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<", y="<<cy1.getY()<<", r="
<<cy1.getRadius()<<", h="<<cy1.getHeight()<<"\narea="<<cy1.area()
<<", volume="<<cy1.volume()<<endl;
cy1.setHeight(15);
cy1.setRadius(7.5);
cy1.setPoint(5,5);
cout<<"\nnew cylinder:\n"<<cy1;
Point &pRef=cy1;
cout<<"\npRef as a point:"<<pRef;
Circle &cRef=cy1;
cout<<"\ncRef as a Circle:"<<cRef;
return 0;
}

转载于:https://www.cnblogs.com/GavinDai/archive/2011/11/14/2248834.html

你可能感兴趣的文章
JS取得绝对路径
查看>>
排球积分程序(三)——模型类的设计
查看>>
HDU 4635 Strongly connected
查看>>
ASP.NET/C#获取文章中图片的地址
查看>>
Spring MVC 入门(二)
查看>>
格式化输出数字和时间
查看>>
页面中公用的全选按钮,单选按钮组件的编写
查看>>
java笔记--用ThreadLocal管理线程,Callable<V>接口实现有返回值的线程
查看>>
BZOJ 1047 HAOI2007 理想的正方形 单调队列
查看>>
各种语言推断是否是手机设备
查看>>
这个看起来有点简单!--------实验吧
查看>>
PHP count down
查看>>
JVM参数调优:Eclipse启动实践
查看>>
(旧笔记搬家)struts.xml中单独页面跳转的配置
查看>>
不定期周末福利:数据结构与算法学习书单
查看>>
strlen函数
查看>>
python的列表与shell的数组
查看>>
关于TFS2010使用常见问题
查看>>
软件工程团队作业3
查看>>
python标准库——queue模块 的queue类(单向队列)
查看>>