简单理解C++的多态公有继承及虚函数

这里用两段简单的代码来介绍C++的多态公有继承和虚函数的简单用法。

代码片段一:

#include<iostream>
#include<cstring>
#define NAMELENGTH 10
using namespace std;
class Human
{
private:
	double m_money;
        char m_name[NAMELENGTH];
public:
	Human(double money, const char* name):m_money(money)
	{
		strncpy(m_name, name, NAMELENGTH-1);
		m_name[NAMELENGTH-1] = '\0';
	}
	~Human(){}
	void name()
	{
		cout<<"name is:" << m_name<<endl;
	}
	char* getname()
	{
		return m_name;
	}
};

class You : public Human
{
public:
	You(double money, char* name):Human(money, name){}
	~You(){}
	void name()
	{
		cout<<"your name is:"<<Human::getname()<<endl;
	}
};

class Me : public Human
{
private:
	int cars;
public:
	Me(double money, const char* name, int c):Human(money, name),cars(c){}
	~Me(){}
	void name()
	{
		cout<<"my name is:"<<Human::getname()<<endl;
		cout<<"I have "<<cars<<" cars"<<endl;
	}
};

int main(void)
{
	Me wuyilun(100000.0, "wuyilun", 100);
<pre name="code" class="html">	wuyilun.name();
Human &who = wuyilun;who.name();Human *who1 = &wuyilun;who1->name();return 0;}

 这里定义了一个Human基类以及继承该Human类的Me和You泛类,Me和You都重写了基类Human中的name()函数。其执行结果如下,可检验一下。 


Human类指针指向Me对象,执行的name()函数依然是Human类里的name()函数,而不是Me对象的name()函数。可见普通的公有继承并不能实现多态。


代码片段一:(通过对代码片段一的简单修改来对比查看虚函数的用法)

#include<iostream>
#include<cstring>
#define NAMELENGTH 10
using namespace std;
class Human
{
private:
	double m_money;
        char m_name[NAMELENGTH];
public:
	Human(double money, const char* name):m_money(money)
	{
		strncpy(m_name, name, NAMELENGTH-1);
		m_name[NAMELENGTH-1] = '\0';
	}
	virtual ~Human(){}
	virtual void name() {};
	char* getname()
	{
		return m_name;
	}
};

class You : public Human
{
public:
	You(double money, const char* name):Human(money, name){}
	~You(){}
	void name()
	{
		cout<<"your name is:"<<Human::getname()<<endl;
	}
};

class Me : public Human
{
private:
	int cars;
public:
	Me(double money, const char* name, int c):Human(money, name),cars(c){}
	~Me(){}
	void name()
	{
		cout<<"my name is:"<<Human::getname()<<endl;
		cout<<"I have "<<cars<<" cars"<<endl;
	}
};

int main(void)
{
	Me wuyilun(100000.0, "wuyilun", 100);
	wuyilun.name();
	You funny(10.0, "funny guy");
	funny.name();
	Human *who = &wuyilun;
	who->name();
	who = &funny;
	who->name();
	return 0;
}
把基类Human中的name()方法变成虚函数,然后在main()函数中通过Human类指针指向Me对象和You对象,调用其name()函数,对比一下和代码片段一的区别。

下面是该代码片段的执行结果。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值