次のコードによって生成されるエラーについて混乱しています。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
ますか?Derived
Base