2016-08-22 5 views
1

私は最近、この世界全体のクラス、継承、および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 apublic:メンバーに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;と一緒に暮らすことができる

+0

'&a :: b'は、メンバへのポインタを形成する特殊な構文です。 '&(a :: b)'を使って簡単なポインタを作ることができます。 – Quentin

+0

@iammilind括弧が追加されると、すべて[よく見えます](http://coliru.stacked-crooked.com/a/a97f5232e5a04c86)。 – Quentin

+0

@クエンティン、はい私は訂正します。しかし、単に '(this-> b)'に置き換えただけでは、問題をより徹底的に解決することができました。この特定の問題については、リンクされた複製には答えがありませんでした。私は再度質問を閉じた。わからない、特定の問題をターゲットにしているときに私の答えを削除する必要があるかどうか。したがって、疑念の恩恵を与えて、それを保持する。 – iammilind

答えて

2

:このような場合には

type **q = &(this->b); // we make sure that `protected: b` is accessed here 

type **q = &a<type>::b; // `protected: b` is not accessible in this context 

を、あなたは実際に継承されたprotectedメンバーとしてbを扱っています。


なぜ、基本クラスにアクセスするためのthisを使用するには?
を参照してください。In a templated derived class, why do I need to qualify base class member names with "this->" inside a member function?


別の方法

当初@Quentinによって連結

を、ポストの下部材に単純なポインタとポインタの違いを示唆している:
Pointer-to-member confusion

だから、元の質問では、実際にはメンバー変数へのポインタを取得しようとしていました次の構文によってLEは:あなたは、おそらく簡単なint*につながる&(a<type>::b)を、望んでいた

&a<type>::b ==> int* a<int>::* 

ながら。
これはノートブックの例の1つで、かっこを適切な場所に置くことの利点を示しています。 :-)

関連する問題