Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;模板类与继承_C++_Templates_Inheritance - Fatal编程技术网

C++ C++;模板类与继承

C++ C++;模板类与继承,c++,templates,inheritance,C++,Templates,Inheritance,可能的重复项: [FAQ] 下面的代码给了我编译错误。怎么了 struct Base { int amount; }; template<class T> struct D1 : public Base { }; template<class T> struct D2 : D1<T> { void foo() { amount=amount*2; /* I am trying to access base class data member

可能的重复项:
[FAQ]

下面的代码给了我编译错误。怎么了

struct Base {
   int amount;
};

template<class T> struct D1 : public Base {
};

template<class T>
struct D2 : D1<T> {
  void foo() { amount=amount*2; /* I am trying to access base class data member */ };
};

int main() {
  D2<int> data;
};


test.cpp: In member function 'void D2<T>::foo()':
test.cpp:11: error: 'amount' was not declared in this scope
struct Base{
整数金额;
};
模板结构D1:公共基{
};
模板
结构D2:D1{
void foo(){amount=amount*2;/*我正在尝试访问基类数据成员*/};
};
int main(){
D2数据;
};
test.cpp:在成员函数“void D2::foo()”中:
test.cpp:11:错误:未在此作用域中声明“amount”
如何解决这个问题


谢谢

这里的问题与如何在继承自模板基类的模板类中查找名称有关。它背后的实际规则是相当神秘的,我对它们一无所知;我通常必须查阅参考资料才能确切地了解为什么这不起作用

解决此问题的方法是显式地为您正在访问的成员添加前缀
this->

void foo() { 
    this->amount = this->amount * 2; // Or: this->amount *= 2;
}
这会给编译器一个明确的提示,说明名称
amount
来自何处,并且应该解决编译器错误


如果有人想更详细地描述发生此错误的原因,我希望看到一个很好的解释。

我以前看过好几次这个问题,但找不到链接。找到了一个,但如果有人能找到一个更好的问题,那就太好了:@Chris:这是一个,这是一个。你注意到D2私下继承了D1吗?不是错误的原因,但可能还有一个错误。@Gorpik-D2实际上是从D1公开继承的,因为它是一个结构,并且结构的默认继承模式是公开的。错误的原因是编译器没有对模板基类成员进行任何假设,以防基类的部分特殊化不存在包括其中一些成员。根据:“关于base,需要注意的一件有趣的事情是,它的成员函数都是在类型T之后创建的。”因此编译器在定义时可能不知道任何成员,而不仅仅是函数。