在C++语言中,只有通过使用指针或引用,并且只有当相关的方法声明为virual时,才可以实现多态消息的传递。为了理解从c++语言的多态规则比其它编程语言更加复杂的原因,需要对面向对象多态变量与内存管理之间的关系进行研究。
#include<iostream>
using namespace std;
class Animal{
public:
virtual void speak(){
cout<<"Animal Speak!"<<endl;
}
void reply()
{
cout<<"Animal Reply!"<<endl;
}
};
class Dog:public Animal
{
public:
virtual void speak()
{
cout<<"woof!"<<endl;
}
void reply()
{
cout<<"woof again!"<<endl;
}
};
class Bird:public Animal{
public:
void speak(){
cout<<"tweet!"<<endl;
}
};
int main(void)
{
Animal *d;
Dog b;
d=&b;
(*d).speak();
Bird c;
d=&c;
d->speak();
return 0;
}