儿童的祖父母超负荷功能 我需要理解为什么如果父函数中声明了重载函数,那么C++中就不允许访问子代重载函数。考虑下面的例子: class grandparent{ public: void foo(); void foo(int); void test(); }; class parent : public grandparent{ public: void foo(); }; class child : public parent{ public: child(){ //foo(1); //not accessible test(); //accessible } };

儿童的祖父母超负荷功能 我需要理解为什么如果父函数中声明了重载函数,那么C++中就不允许访问子代重载函数。考虑下面的例子: class grandparent{ public: void foo(); void foo(int); void test(); }; class parent : public grandparent{ public: void foo(); }; class child : public parent{ public: child(){ //foo(1); //not accessible test(); //accessible } };,c++,overloading,overriding,C++,Overloading,Overriding,这里,两个函数foo()和foo(int)是祖父母中的重载函数。但是foo(int)是不可访问的,因为foo()是在父级中声明的(无论它是公共的、私有的还是受保护的)。但是,test()是可访问的,这在OOP中是正确的 我需要知道这种行为的原因。原因是方法隐藏 在派生类中声明具有相同名称的方法时,将隐藏具有该名称的基类方法。完整签名并不重要(即cv限定符或参数列表) 如果明确希望允许调用,可以使用 using grandparent::foo; 在parent中,想象一个库有这样一个类: st

这里,两个函数foo()和foo(int)是祖父母中的重载函数。但是foo(int)是不可访问的,因为foo()是在父级中声明的(无论它是公共的、私有的还是受保护的)。但是,test()是可访问的,这在OOP中是正确的


我需要知道这种行为的原因。

原因是方法隐藏

在派生类中声明具有相同名称的方法时,将隐藏具有该名称的基类方法。完整签名并不重要(即cv限定符或参数列表)

如果明确希望允许调用,可以使用

using grandparent::foo;

parent

中,想象一个库有这样一个类:

struct Base {
};
在代码中,您将该类用作基类:

struct Derived : Base {
    void f(int);
};
现在你写:

Derived d;
d.f('a');
现在您得到了该库的全新版本2.0,基类也有了一些变化:

struct Base {
    void f(char);
}

如果在这里应用重载,您的代码将被破坏。

是否有理由认为这种行为是件好事?(也就是说,为什么是因为什么原因,而不是为什么是因为什么原因)@SanjayManohar我看到的唯一用途是防止错误——也就是说,认为您是从父级调用方法,而实际上是从祖级调用方法,因为您没有键入参数。您可以使用指令
绕过它。@SanjayManohar参见