C++ 重载、重写、重定义

这两天在学习Java语言,学到继承这一章,想起与C++的不同,遂查找资料温习了一下C++的重载、重写、重定义,留个笔记方便后来查看,目前理解是这样的,如果发现错误再更正。
参考资料:http://glgjing.github.io/blog/2014/12/27/c-plus-plus-zhong-zai-,-zhong-xie-,-zhong-ding-yi-qu-bie/

重载(Overload): 在同一个作用域内,参数列表不同(个数、顺序、参数类型),函数名相同,返回值可相同可不相同。

重写(Override,覆盖)和重定义(Redefining,隐藏)是在不同的作用域,即父子类中。
共同点:函数名相同
先说重定义(Redefining,隐藏),两种情况下:
1、参数不同,不管父类是否是virtual。
2、参数相同,父类不是virtual。

再说重写(Override,覆盖),一种情况:
1、参数相同,父类是virtual,子类可缺省。

总结起来,用伪代码的形式来看:

前提:函数名相同
if(作用域相同){
    if(参数列表不同)
        Overload;
    else
        编译错误;
}
else {
    if(参数列表相同){
        if(父类函数是Virtual)
            Override;
        else
            Redefining;
   }
   else
       Redefining;
}

英文简要的说明:
An overloaded function is a function that shares its name with one or more other functions, but which has a different parameter list. The compiler chooses which function is desired based upon the arguments used.

An overridden function is a method in a descendant class that has a different definition than a virtual function in an ancestor class. The compiler chooses which function is desired based upon the type of the object being used to call the function.

A redefined function is a method in a descendant class that has a different definition than a non-virtual function in an ancestor class. Don’t do this. Since the method is not virtual, the compiler chooses which function to call based upon the static type of the object reference rather than the actual type of the object.

For example, if you have an Animal *george , and george = new Monkey; , where Monkey inherits from Animal, if you say george->dosomething() the Animal.dosomething() method is called, even though george is a Monkey (even if a Monkey.dosomething() method is available).

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值