C++基础之多态实现

#include<iostream>
#include<stdlib.h>
using namespace std;
#define PI 3.14
class Shape{
public:
	Shape() :Area(0), Vol(0){};
	virtual void getArea() = 0;
	virtual void getVol() = 0;
	void output(){
		cout << "面积为" << Area << endl;
		cout << "体积为" << Vol << endl;
	}
protected:
	double Area;
	double Vol;
};
class Circle :public Shape{
public:
	Circle(){
		Radius = 0;
	};
	Circle(double radius) :Radius(radius){};
	void getArea();
	void getVol();
	void setRadius(double radius);
protected:
	double Radius;
};
void Circle::getArea(){
	Area = PI*Radius*Radius;
}
void Circle::getVol(){
	Vol = PI*Radius*Radius*Radius*4/3.0;
}
void Circle::setRadius(double radius){
	Radius = radius;
}
class Rectange :public Shape{
public:
	Rectange(){
		Width = 0;
		Length = 0;
		Height = 0;
	};
	Rectange(double width, double length, double height) :Width(width), Height(height),Length(length){};
	void getArea();
	void getVol();
	void setLength(double length);
	void setWidth(double width);
	void setHeight(double height);
	void setAll(double width, double length, double height);
protected:
	double Width;
	double Height;
	double Length;
};
void Rectange::getArea(){
	Area = Width*Length;
}
void Rectange::getVol(){
	Area = Width*Height*Length;
}
void Rectange::setWidth(double width){
	Width = width;
}
void Rectange::setLength(double length){
	Length = length;
}
void Rectange::setHeight(double height){
	Height = height;
}
void Rectange::setAll(double width, double length, double height){
	Width = width;
	Length = length;
	Height = height;
}
void OutputInformation(Shape *s)
{
	s->getArea();
	s->getVol();
	s->output();
}
class Zhengfang:public Shape{
public:
	Zhengfang(){
		Bian = 0;
	}
	Zhengfang(double bian):Bian(bian){

	}
	void getArea()
	{
		Area = Bian*Bian;
	}
	void getVol()
	{
		Vol = Bian*Bian*Bian;
	}
	void setBian(double bian){
		Bian = bian;
	}
protected:
	double Bian;
};
int main()
{
	Shape *s = new	Zhengfang(1);
	OutputInformation(s);
	system("pause");
}

设计多态这种类之间的关系的时候,切记不变提取,变则单独实现,不针对具体编程,针对接口编程,并针对最小接口编程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值