私は最近、この世界全体のクラス、継承、およびC++のテンプレートに飛びついた。しかし、私は立ち往生した。この問題を解決する方法を教えてください。継承されたクラスメンバ関数の基本クラスメンバのアドレスにアクセスするには?
#include <iostream>
using namespace std;
template <typename type>
class a
{
protected:
type *b;
};
template <typename type>
class p : public a<type>
{
public:
void f()
{
type **q = &a<type>::b;
cout << *q << endl; // some other code in reality related to (*q)
}
};
int main()
{
p<int> obj;
obj.f();
return 0;
}
しかし、それは成功しないことが判明:
x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:9:9: error: ‘int* a<int>::b’ is protected
type *b;
^
x.cpp:18:16: error: within this context
type **q = &a<type>::b;
^
x.cpp:18:26: error: cannot convert ‘int* a<int>::*’ to ‘int**’ in initialization
type **q = &a<type>::b;
^
だから私はtype* a<type>::* q = &a<type>::b;
にtype **q = &a<type>::b;
を変換します。それから私は、追加のエラーを得た:
x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:9:9: error: ‘int* a<int>::b’ is protected
type *b;
^
x.cpp:18:26: error: within this context
type* a<type>::* q = &a<type>::b;
^
x.cpp:19:13: error: invalid use of unary ‘*’ on pointer to member
cout << *q;
^
は、だから私はprotected:
からclass a
のpublic:
メンバーにb
を変換します。しかしそれも私にエラーをもたらします:
x.cpp: In instantiation of ‘void p<type>::f() [with type = int]’:
x.cpp:26:9: required from here
x.cpp:19:13: error: invalid use of unary ‘*’ on pointer to member
cout << *q;
^
私はそれ以上の変更を行うことができません。元のコードが保護されているクラスの特性を改ざんしていないかどうかを知りたいです。あなたのコードの行の下に変更した場合は、まだ、protected: type *b;
と一緒に暮らすことができる
'&a :: b'は、メンバへのポインタを形成する特殊な構文です。 '&(a :: b)'を使って簡単なポインタを作ることができます。 –
Quentin
@iammilind括弧が追加されると、すべて[よく見えます](http://coliru.stacked-crooked.com/a/a97f5232e5a04c86)。 – Quentin
@クエンティン、はい私は訂正します。しかし、単に '(this-> b)'に置き換えただけでは、問題をより徹底的に解決することができました。この特定の問題については、リンクされた複製には答えがありませんでした。私は再度質問を閉じた。わからない、特定の問題をターゲットにしているときに私の答えを削除する必要があるかどうか。したがって、疑念の恩恵を与えて、それを保持する。 – iammilind