多态:一种接口,多种方法(同一种调用方法,根据不同的对象,调用不同类中的函数)
静态联编:非虚函数,在编译时确定好
动态联编: 1. 对象里有指针,指向虚函数表
2. 通过指针,找到表,调用虚函数
3. 图二
4. virtual来定义为虚函数
(一)首先我们来看静态联编,非多态的程序
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
public:
void eating(void) { cout<<"use hand to eat"<<endl; }
};
class Englishman : public Human {
public:
void eating(void) { cout<<"use knife to eat"<<endl; }
};
class Chinese : public Human {
public:
void eating(void) { cout<<"use chopsticks to eat"<<endl; }
};
void test_eating(Human& h)
{
h.eating();
}
int main(int argc, char **argv)
{
Human h;
Englishman e;
Chinese c;
test_eating(h);
test_eating(e);
test_eating(c);
return 0;
}
运行结果,调用的全部是Human中的,并不是我们想要的,因为这里是静态编译进去了,也就是说程序在编译时候就已经确定好就调用Human中的
(二)动态编译,实现多态,在类中定义时候增加virtual来实现这个函数为虚函数
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
public:
virtual void eating(void) { cout<<"use hand to eat"<<endl; }
};
class Englishman : public Human {
public:
virtual void eating(void) { cout<<"use knife to eat"<<endl; }
};
class Chinese : public Human {
public:
virtual void eating(void) { cout<<"use chopsticks to eat"<<endl; }
};
void test_eating(Human& h)
{
h.eating();
}
int main(int argc, char **argv)
{
Human h;
Englishman e;
Chinese c;
test_eating(h);
test_eating(e);
test_eating(c);
return 0;
}
运行结果,就实现了同一接口,不同调用的方法了
(三)更多具体的,,,,,,,