在C++中,如果派生类重新定义了基类成员方法,则所有具有相同名称的基类方法都将隐藏在派生类中。
例如,以下程序无法编译。在下面的程序中,Derived重新定义了Base的fun()方法,这使fun(int i)隐藏。
CPP
#include
using namespace std;
class Base {
public:
int fun() {
cout << "Base::fun() called";
}
int fun(int i)
{
cout << "Base::fun(int i) called";
}
};
class Derived : public Base
{
public:
int fun()
{
cout << "Derived::fun() called";
}
};
// Driver Code
int main()
{
Derived d;
d.fun(5); // Compiler Error
return 0;
}
CPP
#include
using namespace std;
class Base {
public:
int fun()
{
cout << "Base::fun() called";
}
int fun(int i)
{
cout << "Base::fun(int i) called";
}
};
class Derived : public Base {
public:
// Makes Base::fun() and Base::fun(int )
// hidden
int fun(char c)
{
cout << "Derived::fun(char c) called";
}
};
// Driver Code
int main()
{
Derived d;
d.fun('e'); // No Compiler Error
return 0;
}
C++
#include
using namespace std;
class Base
{
public:
int fun()
{
cout<<"Base::fun() called";
}
};
class Derived: public Base
{
public:
using Base::fun;
int fun(char c) // Makes Base::fun() and Base::fun(int ) hidden
{
cout<<"Derived::fun(char c) called";
}
};
int main()
{
Derived d;
d.fun(); // Works fine now 🙂
return 0;
}
即使派生类方法的签名不同,基类中所有重载的方法也会被隐藏。例如,在以下程序中,Derived :: fun(char)使Base :: fun()和Base :: fun(int)都隐藏。
CPP
#include
using namespace std;
class Base {
public:
int fun()
{
cout << "Base::fun() called";
}
int fun(int i)
{
cout << "Base::fun(int i) called";
}
};
class Derived : public Base {
public:
// Makes Base::fun() and Base::fun(int )
// hidden
int fun(char c)
{
cout << "Derived::fun(char c) called";
}
};
// Driver Code
int main()
{
Derived d;
d.fun('e'); // No Compiler Error
return 0;
}
输出
Derived::fun(char c) called
请注意,以上事实对于静态方法和非静态方法都是正确的。
有一种方法可以缓解此类问题。如果我们想重载基类的函数,可以通过使用’using’关键字取消隐藏它。
C++
#include
using namespace std;
class Base
{
public:
int fun()
{
cout<<"Base::fun() called";
}
};
class Derived: public Base
{
public:
using Base::fun;
int fun(char c) // Makes Base::fun() and Base::fun(int ) hidden
{
cout<<"Derived::fun(char c) called";
}
};
int main()
{
Derived d;
d.fun(); // Works fine now 🙂
return 0;
}
输出
Base::fun() called
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。