1.重载overload:函数名相同,参数列表不同。 重载只是在类的内部存在,或者同为全局范围。(同名,同参函数返回值不同时,会编译出错。因为系统无法知晓你到底要调用哪一个。)2.重写override:也叫做覆盖。子类重新定义父类中同名、同参的虚函数。函数特征相同。但是具体实现不同,主要是在继承关系中出现的 。重写需要注意:a 被重写的函数不能是static的。必须是virtual的b 重写函数必须有相同的类型,名称和参数列表c 重写函数的访问修饰符可以不同。尽管virtual是private的,派生类中重写改写为public,protected也是可以的。(因为已经重写了,所以不违背保密性和安全性。)
3.重定义 (redefining):
子类重新定义父类中有相同名称的非虚函数 ( 参数列表可以不同 ) 。
4.隐藏
如果一个类,存在和父类同名的函数,那么无论继承还是重定义,父类的同名函数都会被隐藏。
//
// main.cpp
// TestOveride
//
// Created by New_Life on 2017/4/26.
// Copyright © 2017年 chenhuan001. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class A {
public:
void overload_print(int a) {// 1
cout << "overload A: a" << endl;
}
void overload_print(int a, int b) {// 2,重载1
cout << "overload A: a , b" << endl;
}
/* 编译错误,不能出现重载
* Functions that differ only in their return type cannot be overloaded
* overload_print(1) 的时候,谁知道你调用的什么。
int overload_print(int a) {
return 1;
}
*/
/* 编译错误,static 与 virtual 定义冲突
* 虚函数只能出现在no-static中
* 'virtual' can only appear on non-static member functions
static virtual void virtual_print() {
cout << "virtual A: " << endl;
}
*/
void redefine_print() {//3
cout << "redefine A: " << endl;
}
// -------------- Test hidden ----------------//
void hidden_print() {
cout << "hidden A:" << endl;
}
void hidden_print(int a) {
cout << "hidden A: a" << endl;
}
private:
virtual void override_print() {// 4
cout << "override A: " << endl;
}
void redefine_print(int a) {// 5
cout << "redefine priavte A: a" << endl;
}
};
class B : public A {
public:
void override_print() { //重写(覆盖)了4, private -> public,其实可以看出是一个新的。
cout << "override B: " << endl;
}
void redefine_print() {//重定义 3
cout << "redefine B: " << endl;
}
void redefine_print(int a) {//重定义 5, 说明父类为private的函数也能重定义,也可以看出一个新的。
cout << "redefine B: a" << endl;
}
// ------------- Test hidden -----------------//
void hidden_print(int a, int b) {
cout << "hidden B: a, b" << endl;
}
};
int main(int argc, const char * argv[]) {
B b;
b.overload_print(1, 2); //打印 重载
b.override_print(); //打印 重写
b.redefine_print(); //打印重定义
b.redefine_print(1); //打印重定义,private
/* 编译错误,因为这两个父类的函数,因为同名被隐藏了。使用b.A::hidden_print(), b.A::hidden_print(1)即可
* Too few arguments to function call, expected 2, have 0; did you mean 'A::hidden_print'?
b.hidden_print();
b.hidden_print(1);
*/
b.hidden_print(1, 2);
return 0;
}
原文链接: https://www.cnblogs.com/chenhuan001/p/6767473.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/253088
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!