C++类层次中的同名函数的三种关系:
- 重载(overload)
- 重写(override)
- 隐藏(oversee)
重载
C++函数重载
- 相同的范围内(同一类中)
- 相同的函数名,不同的参数,与返回值类型无关
- virtual关键字可有可无
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A {
public:
int get(int a){
return a;
}
int get(int a, int b){
return a + b;
}
const char *get(const char *a){
return a;
}
};
int main(int argc, char **argv)
{
A a;
cout << a.get(100) << endl; //100
cout << a.get(100,200) << endl; //300
cout << a.get("hello world") << endl; //hello world
system("pause");
return 0;
}
重写
C++函数重写
- 在不同类中(派生类与基类中)
- 相同的函数名
- 相同的参数
- 相同的返回值
- 基类中必须有virtual关键字
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A {
public:
//此处有virtual关键字
virtual void get(int a){
cout << "A int get " << a << endl;
}
};
class B :public A{
public:
/*子类重写父类void get(int)*/
void get(int a) {
cout << "B int get " << a << endl;
}
};
int main(int argc, char **argv)
{
B b;
A *ptr = &b;
ptr->get(100);//此处触发多态 B int get 100
system("pause");
return 0;
}
隐藏
C++函数隐藏
- 两个函数参数相同,但是基类不是虚函数。和重写的区别在于基类函数是否是虚函数
- 两个函数参数列表不同,无论基类函数是否虚函数,基类函数都将被派生类覆盖。和重载的区别在于两个函数不在同一个类中
//隐藏的第一种情况1
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A {
public:
void get(int a){
cout << "A int get " << a << endl;
}
};
class B :public A{//B类继承A类
public:
void get(int a) {
cout << "B int get " << a << endl;//B中的get函数覆盖了A中的get函数
}
};
int main(int argc, char **argv)
{
B b;
b.get(100); //B int get 100
b.A::get(100); //A int get 100
system("pause");
return 0;
}
//隐藏的第一种情况2
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A {
public:
void get(int a) {
cout << "A int get " << a << endl;
}
};
class B :public A {//B类继承A类
public:
//基类没有添加virtual关键字,所以没有发生多态,A中的get被隐藏
virtual void get(int a) {
cout << "B int get " << a << endl;
}
};
int main(int argc, char **argv)
{
B b;
A *ptr = &b;
ptr->get(100); //没有触发多态,所以打印结果为:A int get 100
system("pause");
return 0;
}
//隐藏的第二种情况
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class A {
public:
void get(double a){
cout << "A int get " << a << endl;
return;
}
};
class B :public A{
public:
void get(int a) {
cout << "B int get " << a << endl;//覆盖了A中的get函数
return;
}
};
int main(int argc, char **argv)
{
B b;
b.get(3.14); //B int get 3
b.A::get(3.14); //A int get 3.14
system("pause");
return 0;
}