虚函数与多态:目的是让父类指针可以调用子类的同名方法。
1.先看源码,test.cpp
#include <iostream>
using namespace std;
namespace mytest{
class father{
public:
virtual void common(){ //有无这个virtual,对引用(后边p1和p2影响)
cout << "this is father!" <<endl;
};
};
class son: public father{
public:
void common(){
cout << "this is son!" <<endl;
};
};
}
using namespace mytest;
int main(){
son *s = new son();
s->common();
father f;
f.common();
father *p1 = s;
p1->common();
father *p2 = &f;
p2->common();
return 0;
}
2.g++ -o test test.cpp
3./test
看看不加virtual的结果:
this is son!
this is father!
this is father!
this is father!
看看加virtual的i结果:
this is son!
this is father!
this is son!
this is father!