C++ 多态

1.概念

类有三个重要的性质-封装、 继承、多态。其中多态有点难理解

通俗的说接口的多种不同实现方式即为多态(允许你将父对象设置成为一个或者更多的他的子对象相等的技术),赋值之后父对象就可以根据当前子对象给他的赋值,以子对象的特性(以子对象的方式)运行。

class food
{
public:
	void price()
	{
	cout<<"the food price"<<endl;
	}
	void weight()
	{
	cout<<"the food weight"<<endl;

	}

private:
	int chengben;

};

class vegetables: public food
{
	void price()
	{
	cout<<"the vegetables price"<<endl;

	}

private:
	int chengben;

};

int main()
{
	vegetables shucai;
	food *shiwu=&shucai;
	shiwu->price();
	return 0;

}

上面输出的结果是

the food price


为什么把子类的地址给父类的指针后执行的仍然不是子类的属性和方法呢?

这里就要讲多态的问题

上面的例子根本没实现类的多态,要想实现有什么方法呢?引入虚函数

class food
{
public:
	virtual void price()
	{
	 cout<<"the food price"<<endl;
	}
	void weight()
	{
	cout<<"the food weight"<<endl;

	}

private:
	int chengben;

};

class vegetables: public food
{
	void price()
	{
	cout<<"the vegetables price"<<endl;

	}

private:
	int chengben;

};

int main()
{
	vegetables shucai;
	food *shiwu=&shucai;
	shiwu->price();
	return 0;

}

输出的结果是

the vegetables price

这样就实现了类的多态---父类的对象通过不同的赋值,达到实现子类的不同的状态。



C++的多态性:在基类的函数前加vitual关键字,在派生类中重写该函数(不用加vitual),运行时将会根据对象的实际类型来调用相应的函数。如果对象类型是子类,就调用子类的函数,如果对象类型是父类,就调用父类的函数。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值