子级中的祖父母重载函数

Grandparent overloaded function in child

本文关键字:重载 函数 祖父母      更新时间:2023-10-16

我需要理解,如果任何重载函数在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);
}

如果在这里应用重载,您的代码就会中断。