1. 前言
继承是面向对象编程的重要特性,在c++中,当父类与子类出现同名函数时,会出现两种情况:覆写和隐藏,本文主要讨论c++中这两种情况的特点和使用区别
2. 共性
当子类继承父类,并且子类中有父类同名函数,那么子类将隐藏父类中所有同名函数,不可以对父类中同名函数直接进行访问,此时子类调用父类中函数需要用域操作符::
#include<iostream>
using namespace std;
class A{
public:
void fun1(){
cout<<"A::fun1()"<<endl;
}
void fun1(int){
cout<<"A::fun1(int)"<<endl;
}
void fun2(){
cout<<"A::fun2()"<<endl;
}
};
class B:public A{
public:
void fun1(){
cout<<"B::fun1()"<<endl;
}
};
int main(){
B b;
b.fun1();//调用子类b的fun1()函数
//b.fun1(3);尝试调用父类fun1(int)函数会报错:error:no matching function for call to 'B::fun1(int)'
b.A::fun1();//调用父类A的fun1()函数
b.A::fun1(3);//调用父类A的fun1(int)函数
b.fun2();//调用父类A的fun2()函数
return 0;
}