我有这个代码:
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/