Virtual function && function overriding && overload

今天想了半天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(函数重载),三个完全不同的概念,有的时候一急就容易混。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值