【发布时间】:2011-02-05 08:29:38
【问题描述】:
我对@987654321@ 产生的错误感到困惑。 在 Derived::doStuff 中,我可以通过调用直接访问 Base::output。
为什么我不能在可以调用 output() 的同一上下文中创建指向 output() 的指针?
(我认为受保护/私有管理是否可以在特定上下文中使用名称,但显然这是不完整的?)
我写callback(this, &Derived::output);而不是callback(this, Base::output)是正确的解决方案吗?
#include <iostream>
using std::cout; using std::endl;
template <typename T, typename U>
void callback(T obj, U func)
{
((obj)->*(func))();
}
class Base
{
protected:
void output() { cout << "Base::output" << endl; }
};
class Derived : public Base
{
public:
void doStuff()
{
// call it directly:
output();
Base::output();
// create a pointer to it:
// void (Base::*basePointer)() = &Base::output;
// error: 'void Base::output()' is protected within this context
void (Derived::*derivedPointer)() = &Derived::output;
// call a function passing the pointer:
// callback(this, &Base::output);
// error: 'void Base::output()' is protected within this context
callback(this, &Derived::output);
}
};
int main()
{
Derived d;
d.doStuff();
}
编辑:我很想知道这在标准中的位置,但大多数情况下我只是想围绕这个概念来思考一下。我认为我的问题是callback 无权访问Derived 的受保护成员,但如果您将指针传递给它,它可以调用Derived::output。来自Derived 的Derived 的受保护成员与来自Base 的Derived 的受保护成员有何不同?
【问题讨论】:
-
+1,我很确定我最近阅读了答案但找不到它......希望一些当地的大师/标准能够启发我们。
标签: c++ access-modifiers