多态和虚函数

先看两个例子

class C
{
public:
	string toString()
	{
		return "class c";
	}
};

class B : public C
{
	string toString()
	{
		return "class B";
	}
};

class A : public B
{
	string toString()
	{
		return "class A";
	}
};


void displayObject(C p)
{
	cout<<.toString()<<endl;
}

int main()
{
	displayObject(A());
	displayObject(B());
	displayObject(C());
	
	system("pause");

	return 0;
}

输出结果如下:<p>class C</p><p>class C</p><p>class C</p>

    由于形参的类型是 C,因此,调用的总是 C 中定义的 toString 函数,三次函数调用的输出都是相同的结果。

    如果调用 displayObject(A()) 时 A 中定义的 toString() 被调用,如果调用如果调用 displayObject(B()) 时 B 中定义的 toString() 被调用, displayObject(C()) 时 C 中定义的 toString() 被调用,为了达到这个目标,只要使用虚函数和指针变量修改上面程序即可。

class C
{
public:
	virtual string toString()
	{
		return "class c";
	}
};

class B : public C
{
	string toString()
	{
		return "class B";
	}
};

class A : public B
{
	string toString()
	{
		return "class A";
	}
};


void displayObject(C *p)
{
	cout<<p->toString()<<endl;
}

int main()
{
	A a=A();
	B b=B();
	C c=C();

	displayObject(&a);
	displayObject(&b);
	displayObject(&c);
	
	system("pause");

	return 0;
}

输出结果为:
class A
class B
class C

    把 类 C 中的 toString() 定义为虚函数, displayObject() 里定义了一个类型为 C 的指针变量 P,当调用 displayObject(&a)时,对象 A() 的地址被传递给 p。调用 p->toStrinfg()时, c++会动态地确定使用哪个 toString()函数,由于 p 指向 类 A 的一个对象,A 中被定义的 toString() 被调用。
    在运行时确定调用哪个函数的能力称为 动态绑定(dynamic binding), 它还有一个更常用的名称---- 多态(polymorphism,源于希腊语,含义为“许多形式”),因为一个函数有多种实现。

    在c++中,在派生类中重定义一个虚函数,称为 函数覆盖。一个函数在基类中定义为虚函数,在派生类中自动的被认为是虚函数,不必在派生类的函数声明中加上关键字 Virtual


为使一个函数能动态绑定,需要做两件事:

(1)在基类中,函数必须被声明为虚函数

(2)函数中应用对象的变量必须包含对象的地址


上面 的程序是将对象的地址传递给一个指针,可将函数参数改为基类的应用类型

void displayObject(C &p)
{
	cout<<p.toString()<<endl;
}

int main()
{
	A a=A();
	B b=B();
	C c=C();

	displayObject(a);
	displayObject(b);
	displayObject(c);
	
	system("pause");

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值