c++ - 指向具有 protected 继承的基类方法的指针

标签 c++ inheritance

我有这个代码:

class Foo
{
public:
    int x = 4;
    int & operator[](size_t index) { return x; }
};

class Bar : protected Foo
{
public: 
    using Foo::operator[];

    Bar () { x++; }
};

int main(int agrc, char ** argv)
{
    typedef int &(Bar::*getOp)(size_t index);

    Bar b;
    auto bVal = b[4];
    getOp o = &Bar::operator[]; 
    auto bVal2 = (b.*o)(7);
}

但是,我不能编译它,因为

error C2247: 'Foo' not accessible because 'Bar' uses 'protected' to inherit from 'Foo'

当我使用 using 并且我可以直接调用运算符(operator)时,为什么这是不可能的?有什么办法吗?

如果我将继承更改为公共(public),它会起作用。

注意:这只是更大类的一个例子。我不想使用公共(public)继承,因为我不想能够执行 Foo f = Bar() 因为在 Bar 中,我隐藏了父方法(我没有使用虚拟)。

最佳答案

Why is this not possible, when I have used using and I can call operator directly?

using 声明使您可以访问名称 operator[]。但它不会改变成员的类型。它留下来 int &(Foo::*)(size_t)。注意 Foo

因此转换为o声明 类型需要沿继承树向下转换。此转换必须检查目标类确实是从基类派生的,但这是一个不可访问的基类。

解决它的一种方法是为 Bar 提供一个返回该指针的成员函数。在 Bar 的范围内,转换可以访问基类。此外,这种转换需要 static_cast

关于c++ - 指向具有 protected 继承的基类方法的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56170132/

相关文章:

c++ - 指针数组 vs ** : why does one give an error?

ruby - Ruby 父类(super class)中实用方法的放置位置

c++ - 如何将指向基类成员的指针转换为指向派生类相同成员的指针

c++ - 最简单最整洁的c++11 ScopeGuard

java - 将嵌套类继承到子类

c# - 为什么在基类引用中存储派生类型是合法的?

C++ 模板,模棱两可的重载

c++ - 部分函数/方法模板特化解决方法

c++ - Qt获取信号调用者并逐行从文件中读取

c++ - Windows 线程池, 'PTP_CALLBACK_INSTANCE' : undeclared identifier