重载函数隐藏在派生类中 [英] overloaded functions are hidden in derived class
问题描述
在派生类中如果我从一个基类重定义/重载一个函数名,
那么这些重载的函数不能访问/派生类可见。
为什么这是??
In a derived class If I redefine/overload a function name from a Base class,
then those overloaded functions are not accessable/visible to derived class.
Why is this??
如果我们不从派生类
中的基类重载oveloaded函数,那么该函数的所有重载版本都可用于派生类
对象,为什么是这个?
这是什么原因。如果你在编译器和链接器级别
中解释这将对我更有帮助。
If we don't overload the oveloaded function from the base class in derived class
then all the overloaded versions of that function are available to derived class
objects, why is this??
what is the reason behind this. If you explain this in compiler and linker level
that will be more helpful to me. is it not possible to support this kind of scinario??
Edited
For examble:
class B
{
public:
int f() {}
int f(string s) {}
};
class D : public B
{
public:
int f(int) {}
};
int main()
{
D d;
d.f(1);
//d.f(string); //hidden for D
}
Now object 'd' can't access f() and f(string).
推荐答案
TTBOMK这没有真正的技术原因,只是Stroustrup,在创建语言时,认为这是更好的默认。 (在这里它类似于规则,右值不隐式绑定到非< - > const
引用。)
TTBOMK this doesn't have a real technical reason, it's just that Stroustrup, when creating the language, considered this to be the better default. (In this it's similar to the rule that rvalues do not implicitly bind to non-const
references.)
可以很容易地解决它明确将基类版本带到派生类的范围:
You can easily work around it be explicitly bringing base class versions into the derived class' scope:
class base {
public:
void f(int);
void g(int);
};
class derived : public base {
public:
using base::f;
void f(float);
void g(float); // hides base::g
};
或通过显式调用:
derived d;
d.base::g(42); // explicitly call base class version
这篇关于重载函数隐藏在派生类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!