函数重载(overload)
函数重载是指在一个类中声明多个名称相同但参数列表不同的函数,这些的参数可能个数或顺序,类型不同,但是不能靠返回类型来判断。特征是:
(1)相同的范围(在同一个作用域中);
(2)函数名字相同;
(3)参数不同;
(4)virtual 关键字可有可无(注:函数重载与有无virtual修饰无关);
(5)返回值可以不同;
函数重写(也称为覆盖 override)
函数重写是指子类重新定义基类的虚函数。特征是:
(1)不在同一个作用域(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有 virtual 关键字,不能有 static 。
(5)返回值相同,否则报错;
(6)重写函数的访问修饰符可以不同;
重定义(也称隐藏)
(1)不在同一个作用域(分别位于派生类与基类) ;
(2)函数名字相同;
(3)返回值可以不同;
(4)参数不同。此时,不论有无 virtual 关键字,基类的函数将被隐藏(注意别与重载以及覆盖混淆);
(5)参数相同,但是基类函数没有 virtual关键字。此时,基类的函数被隐藏(注意别与覆盖混淆);
//
// 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;
}