今天想了半天Virtual Function 和 Function overriding 的区别
后来发现Virtual Function 的好处是,
This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child!
Here is an example: Assuming you have class "Child" and class "Child2" and "Child3" you want to be able to refer to them through their base class (Parent).
实验代码如下:class SomeClass {
public:
virtual void virtualf() {
cout<<"parent";
}
};
class derivedcalss :public SomeClass {
public:
void virtualf() {
cout<<"children"<<endl;
}
};
int main(int argc, const char * argv[]) {
SomeClass a;
derivedcalss b;
SomeClass* p;
p = &b;
p->virtualf();
return 0;
}
再看输出,
children
这就是virtual 的好处,如果不加virtual的话,输出的会是“Parent”。
对于一个父类的所有继承类来说,他们的一切实例的方法,均可以用parent* p-> virtualf(); 的方法来调用,即使你不知道他是一个子类。
最后,virtual (虚函数),overriding(函数覆盖),overloading(函数重载),三个完全不同的概念,有的时候一急就容易混。。