抽象类的作用

//抽象类
//如果一个类中至少有一个纯虚函数,则为抽象类。其目的是用它作为基类建立派生类。
//1.由于抽象类中至少有一个没有定义功能的纯虚函数,因此,抽象类只能作为其他类的基类来使用,
// 不能建立抽象类对象。
// 2.不可从具体类派生出抽象类,(没有纯虚函数的普通类)
//3.抽象类不能用做函数的参数类型,返回类型或显示转换的类型。
//4.可以声明指向抽象类的指针或引用(抽象类 *指针;或抽象类 &a;),此指针可以指向它的派生类,实现多态性。
//5.如果派生类没有实现纯虚函数,只继承基类纯虚函数,则这个类仍为抽象类,若实现纯虚函数,则为具体类。
//例如:抽象类的应用
#include<iostream>
using namespace std;
class Shape{
public:
	Shape(double x)
	{
		r=x;
	}
	virtual void Area()=0;//纯虚函数
	virtual void Perimeter()=0;
protected:
	double r;
};
class Circle:public Shape{
public:
	Circle(double x):Shape(x)
	{}
	void Area(); //在派生类中声明纯虚函数
	void Perimeter();
};
void Circle::Area()  //实现纯虚函数
{
	cout<<"The circle's Area is: ";
	cout<<3.14*r*r<<endl;
}
void Circle::Perimeter()
{
	cout<<"The circle's Perimeter is: ";
	cout<<2*3.14*r<<endl;
}
class In_Square:public Shape{
public:
	In_Square(double x):Shape(x)
	{}
	void Area();
	void Perimeter();
};
void In_Square::Area()
{
	cout<<"The In_Square's Area is: ";
	cout<<2*r*r<<endl;
}
void In_Square::Perimeter()
{
	cout<<"The In_Square's Perimeter is: ";
	cout<<4*1.414*r<<endl;
}
class Ex_Squrae:public Shape{
public:
	Ex_Squrae(double x):Shape(x)
	{}
	void Area();
	void Perimeter();
};
void Ex_Squrae::Area()
{
	cout<<"The Ex_Squrae's Area is: ";
	cout<<4*r*r<<endl;
}
void Ex_Squrae::Perimeter()
{
	cout<<"The Ex_Squrae's Perimeter is: ";
	cout<<8*r<<endl;
}
int main()
{
	Shape *ptr;//定义抽象类Shape的指针
	Circle c(6);
    In_Square In(6);
	Ex_Squrae Ex(6);
	ptr=&c;   //  抽象类Shape 的指针ptr指向派生类的对象c
	ptr->Area();
	ptr->Perimeter();
	ptr=&In;
	ptr->Area();
	ptr->Perimeter();
	ptr=&Ex;
	ptr->Area();
	ptr->Perimeter();
	return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值