C++中的继承、多态

 1、虚函数:关键字为:virtual,在基类中声明,可以在派生类中重写,在声明的后面添加 = 0

可以将该函数声明为纯虚函数(在基类中声明,但是没有提供任何实现,实现即代码逻辑)但是在派生类中,继承基类的纯虚函数必须提供具体的实现,简单来说,在基类中没有提供实现,在派生类中使用就要提供实现。

语法:virtual 数据类型 函数名() const = 0;

2、基类指针:可以在运行时,根据派生类对象的实际类型调用相应的函数。

基类指针的写法:基类名 *指针名 = &派生类的对象

如 shape *shap1= &c   shape为基类名, shape1为自己创建的指针名,c为派生类circle的对象c

这表示基类指针shape1指向派生类的对象circle

shape1->printtype(); 表示使用指针shape1调用成员函数printtype(),但是由于shape1指向派生类对象c,所以在调用的时候,是调用的派生类circle中的printtype()函数,这叫做多态性

3、继承:

语法:class 派生类名 :权限(如public) 基类名

#include<iostream>
using namespace std;
class Shape
{
public:
	Shape() {}
	virtual double Area() const = 0;
	virtual void printtype() const
	{
		cout << "This is shape" << endl;
	}
};
class circle : public Shape
{
private :
	double r;
public:
	circle(double _r) :r(_r) {}
	double Area() const override
	{
		return 3.1415926 * r * r;
	}
	void printtype() const
	{
		cout << "This is a circle!" << endl;
	}
};
class rectangle:public Shape
{
private:
	double length;
	double width;
public:
	rectangle(double l, double w) :length(l), width(w) {}
	double Area() const override
	{
		return length * width;
	}
	void printtype()const
	{
		cout << "This is a rectangle!" << endl;
	}
};
int main()
{
	circle s1(5.0);
	rectangle s2(4.0, 6.0);
	Shape* shape1 = &s1;
	Shape* shape2 = &s2;
	
	shape1->printtype();
	cout << "Area of circle:" << shape1->Area() << endl;

	shape2->printtype();
	cout << "Area of rectangle:" << shape2->Area() << endl;

	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值