这段代码:
class B {
protected:
void Foo(){}
}
class D : public B {
public:
void Baz() {
Foo();
}
void Bar() {
printf("%x\n", &B::Foo);
}
}
给出这个错误:
t.cpp: In member function 'void D::Bar()':
Line 3: error: 'void B::Foo()' is protected
- 为什么我可以调用 protected 方法,但不能获取其地址?
- 有没有办法标记可以从派生类完全访问的东西,而不是只能从派生类和与所述派生类相关?
顺便说一句:This looks related但我正在寻找一个引用,以说明在规范等中调用它的位置(希望这将导致如何让事情按我期望的方式工作)。
最佳答案
您可以通过D
获取地址通过写 &D::Foo
, 而不是 &B::Foo
.
看到这个编译正常:http://www.ideone.com/22bM4
但这不能编译(你的代码):http://www.ideone.com/OpxUy
为什么我可以调用 protected 方法但不能获取其地址?
你不能通过写 &B::Foo
来获取它的地址因为Foo
是 protected 成员,您无法从外部访问它B
,甚至没有它的地址。但是写 &D::Foo
,你可以,因为 Foo
成为 D
的成员通过继承,你可以得到它的地址,无论它是私有(private)的、 protected 还是公共(public)的。
&B::Foo
与 b.Foo()
具有相同的限制和 pB->Foo()
有,在以下代码中:
void Bar() {
B b;
b.Foo(); //error - cannot access protected member!
B *pB = this;
pB->Foo(); //error - cannot access protected member!
}
在 ideone 看到错误:http://www.ideone.com/P26JT
关于c++ - 访问 protected 方法的方法指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5822421/