继承在使用模板时不起作用

时间:2013-04-09 01:47:52

标签: c++ templates inheritance this

我遇到了继承问题。我创建此示例以显示或多或少的问题。问题是如果我公开派生自公开派生的类,那么我必须一直访问原始类中的受保护成员。但是,当我使用模板时,情况似乎并非如此。

事实上,下面的例子抱怨'n ++;'说'n'没有在范围内宣布。但是,如果我没有模板的话。代码编译得很好。发生了什么事?

#include<iostream>
template<typename T> 
class base{
 protected:
    T n;
 public:
    T getn();
    base();
};

template<typename T>  
T base<T>::getn(){
   return n; 
}

template<typename T> 
base<T>::base(){
   n = 8; 
}

template<typename T> 
class daddy: public base<T>{
protected: 
public:
};

template<typename T>
class granny: public daddy<T>{
protected:
public:
    T plusone();
};

template<typename T> 
T granny<T>::plusone(){ 
    //this->n = this->n + 1;
   n++;
   return n;
}

int main(){
   granny<int> oldmommy;

   int su = oldmommy.getn();   
   std::cout << su << std::endl;
   su = oldmommy.plusone();
   std::cout << "plusone" << su << std::endl;
   return 0;
}

顺便说一下。告诉我是否应该发布没有模板进行比较的代码..

2 个答案:

答案 0 :(得分:3)

快速解决方法是在变量之前应用this

 this->n = this->n + 1;
 return this->n;

原因是编译器没有假设模板基类成员(在这种情况下为n,这取决于类型T),以防基类的部分特化而不包括其中一些成员。

答案 1 :(得分:2)

n此处为dependent name。您必须明确指出n来自哪里,否则编译器不知道您指的是n(注意可能有一些base专门化没有名为n)的成员。

您可以使用以下方法实现此目的:

this->n;

或者:

base<T>::n;

而不是代码中的n

相关问题