我对以下代码生成的错误感到困惑。在 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
,它就可以调用。that from 的 protectedDerived::output
成员与that from 的 protected 成员有何不同?Derived
Derived
Derived
Base