This question already has answers here:
Function with same name but different signature in derived class
(2个答案)
3年前关闭。
我需要了解,如果在Parent中声明了任何重载函数,为什么C++不允许在Child中访问祖 parent 重载函数。考虑以下示例:
在这里,两个函数foo()和foo(int)是Grandparent中的重载函数。但是foo(int)是不可访问的,因为foo()是在Parent中声明的(无论声明的是public还是private或protected都无关紧要)。但是,根据OOP,可以访问test()。
我需要知道这种行为的原因。
里面
(2个答案)
3年前关闭。
我需要了解,如果在Parent中声明了任何重载函数,为什么C++不允许在Child中访问祖 parent 重载函数。考虑以下示例:
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
}
};
在这里,两个函数foo()和foo(int)是Grandparent中的重载函数。但是foo(int)是不可访问的,因为foo()是在Parent中声明的(无论声明的是public还是private或protected都无关紧要)。但是,根据OOP,可以访问test()。
我需要知道这种行为的原因。
最佳答案
原因是方法隐藏了。
在派生类中声明具有相同名称的方法时,具有该名称的基类方法将被隐藏。完整签名无关紧要(即cv限定词或参数列表)。
如果您明确希望允许通话,则可以使用
using grandparent::foo;
里面
parent
。