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

来源:互联网 发布:ubuntu软件更新器 编辑:程序博客网 时间:2024/05/18 20:36

这两天在学习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