C++ 多态

C++ 多态

虚函数
虚函数 是在基类中使用关键字 virtual 声明的函数。
在派生类中重新定义基类中定义的虚函数时,
会告诉编译器不要静态链接到该函数。

我们想要的是在程序中任意点
可以根据所调用的对象类型来
选择调用的函数,
这种操作被称为动态链接,或后期绑定。
area() 的声明前放置关键字 virtualclass Shape
{
	protected:
		int width, height;
	public:
		Shape(int a = 0, int b = 0) {
			width = a;
			height = b;
		}
		virtual int area ()
		{
			cout << "parent Shape area" << endl;
			return 0;
		}
	private:

};
class Recrangle : public Shape
{
	public :
		Recrangle(int a = 0, int b = 0) : Shape(a, b) 
		{

		}
		int area()
		{
			cout << "child Recrangle area" << endl;
			return 0;
		}
};
class Triangle : public Shape
{
	public :
		Triangle(int a = 0, int b = 0) :Shape(a, b) 
		{

		}
		int area()
		{
			cout << "traingle class area:" << endl;
			return (width * height / 2);
		}
};
int main()
{
	Shape* shape;
	Recrangle rec(10, 7);
	Triangle tri(10, 5);

	//存储矩形的地址
	shape = &rec;

	//调用矩形的求面积函数 area
	shape->area();

	//存储三角形的地址
	shape = &tri;
	
	//调用三角形的求面积函数 area
	shape->area();
	return 0;
}

打印结果:
child Recrangle area
traingle class area:

纯虚函数

您可能想要在基类中定义虚函数,
以便在派生类中重新定义该函数更好地适用于对象,
但是您在基类中又不能对虚函数给出有意义的实现,
这个时候就会用到纯虚函数。

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      // pure virtual function
      virtual int area() = 0;
};

= 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ob杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值