关于多态(polymorphism)的初步知识(此处指动态多态)

#include <iostream>
using namespace std;

class Human
{
public:
	virtual void eat()
	{
		cout << "Human: virtual void eat()" << endl;
	}

	void sleep() // 非虚函数,不具有多态性
	{
		cout << "Human: void sleep()" << endl;
	}
};

class Man : public Human
{
public:
	virtual void eat() // 此处的virtual可省略,但最好不要省略
	{
		cout << "Man: virtual void eat()" << endl;
	}

	void sleep()
	{
		cout << "Man: void sleep()" << endl;
	}
};

int main()
{
	Human *p, h;
	Man m;

	p = &h;
	p->eat();
	p->sleep();

	p = &m;
	p->eat();
	p->sleep();

	return 0;
}

      结果为:

Human: virtual void eat()
Human: void sleep()
Man: virtual void eat()
Human: void sleep()
 

      多态(动态多态)条件:1. 发生在基类和派生类之间;2.都是虚函数;3.函数首部要相同(注意:如果返回值类型不同,则会报错啊,我以前不知道这一点,还以为即使返回值不一样,也可以通过晚绑定来实现多态呢!)。

      上面的程序也可以改成引用形式:

 

#include <iostream>
using namespace std;

class Human
{
public:
	virtual void eat()
	{
		cout << "Human: virtual void eat()" << endl;
	}

	void sleep() // 非虚函数,不具有多态性
	{
		cout << "Human: void sleep()" << endl;
	}
};

class Man : public Human
{
public:
	virtual void eat() // 此处的virtual可省略,但最好不要省略
	{
		cout << "Man: virtual void eat()" << endl;
	}

	void sleep()
	{
		cout << "Man: void sleep()" << endl;
	}
};

void testEat(Human & b)
{
	b.eat();
}

void testSleep(Human & b)
{
	b.sleep();
}

int main()
{
	Human h;
	Man m;

    testEat(h);
	testSleep(h);

	testEat(m);
	testSleep(m);

	return 0;
}

 

    结果为指针形式的结果一样。在下面的讨论中,我们采用指针的形式,继续看程序:

 

#include <iostream>
using namespace std;

class Human
{
public:
	virtual void eat()
	{
		cout << "Human: virtual void eat()" << endl;
	}
};

class Man : public Human
{
public:
	// error C2555: 'Man::eat' : overriding virtual function differs 
	// from 'Human::eat' only by return type or calling convention
	virtual int eat()
	{
		cout << "Man: virtual int eat()" << endl;
	}
};

int main()
{
	Human *p, h;
	Man m;

	p = &h;
	p->eat();

	p = &m;
	p->eat();

	return 0;
}

     由上面的程序可知,仅仅返回值不同,会报错啊(我以前以为这样也可以有多态性呢)。继续看:

#include <iostream>
using namespace std;

class Human
{
public:
	virtual void eat(int a)
	{
		cout << "Human: virtual void eat(int a)" << endl;
	}
};

class Man : public Human
{
public:
	virtual void eat(float a) // 不具有多态性
	{
		cout << "Man: virtual void eat(float a)" << endl;
	}
};

int main()
{
	Human *p, h;
	Man m;

	p = &h;
	p->eat(1);

	p = &m;
	p->eat(1);

	return 0;
}

     结果为:

 

Human: virtual void eat(int a)
Human: virtual void eat(int a)

     现在,总该对多态有基本的认识了吧。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值