子级中的祖父母重载函数
Grandparent overloaded function in child
我需要理解,如果任何重载函数在Parent中声明,C++为什么不允许访问Child中的Grandparent重载函数。考虑以下示例:
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)。然而,test()是可访问的,这是OOP的正确做法。
我需要知道这种行为的原因。
原因是方法隐藏。
在派生类中声明具有相同名称的方法时,具有该名称的基类方法将被隐藏。完整签名无关紧要(即cv限定符或参数列表)。
如果您明确希望允许呼叫,可以使用
using grandparent::foo;
在CCD_ 1内部。
假设一个库有这样的类:
struct Base {
};
在代码中,您使用该类作为基类:
struct Derived : Base {
void f(int);
};
现在你写:
Derived d;
d.f('a');
现在你得到了这个库的2.0版本,基类也发生了一些变化:
struct Base {
void f(char);
}
如果在这里应用重载,您的代码就会中断。
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?