2017-02-05 6 views
2

テンプレート付き派生クラスで多態性を実装しようとしています。以下を参照してください。テンプレートによる継承を使用した純粋仮想関数

//templated base class 
template <class num> class A{ 
protected: 
    num x; 
    num y; 

public: 
    A(num x0 = 0, num y0 = 0) { 
     x = x0; 
     y = y0; 
    } 
    virtual void print_self() = 0; 

}; 

//derived class 
template < class num > class B: public A <num> { 
    public: 
     B(num x1 = 0, num y1 = 0):shape <num> (x1 , y1) { } 
     void print_self(){ 
      std::cout << "x is " << x << " and y is " << y << endl; 
     } 
}; 

基本クラスは、純粋な仮想関数print_self()を持っています。 yの

'x' was not declared in this scope 

同じ:派生クラスで関数を定義しようとすると、私は次のエラーを受け取りました。 したがって、派生クラスはprotectedとしてリストされていても、変数xとyにアクセスできません。

print_self()を定義する他の方法はありますか?これは簡単ではありませんか?それが不可能な場合は、別のアプローチを提案できますか?

+0

使用 'this-> X 'と' this-> y'。 – skypjack

+0

ここで 'this'の使用は冗長です。 – Raindrop7

+0

'A :: x'と' A :: y'や 'typedef A base'と' base :: x'などを使うこともできます。 – DeiDei

答えて

2

テンプレート継承を使用しているため、xyの存在はテンプレート引数に依存します。つまり、thisポインタの基底クラス部分は従属名になります。 thisポインターを明示的に使用するか、またはusingを使用する必要があります。

template<typename num> 
struct B : A<num> { 
    using A<num>::x; 
    using A<num>::y; 

    void print_self(){ 
     std::cout << "x is " << x << " and y is " << y << endl; 
    } 
}; 

あるいは:

template<typename num> 
struct B : A<num> { 
    void print_self() { 
     std::cout << "x is " << this->x << " and y is " << this->y << endl; 
    } 
}; 
関連する問題