#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)
现在,总该对多态有基本的认识了吧。