我有一个简单的 C++ 程序,我无法编译它,尽管我尝试在 google 中搜索并尝试阅读有关模板、继承和 vector 的内容,但我没有任何线索知道我犯了什么错误, 谁能帮帮我吗!! 以下是代码:
template <class T>
class Base
{
public:
int entries;
};
template <class T>
class Derive : public Base<T *>
{
public:
int j;
void pankaj(){j = entries;}
void clear();
};
template <class T> void Derive<T>::clear()
{
int i;
int j=entries;
};
int main()
{
Derive b1;
}
我收到以下错误: pankajkk> g++ 示例.cpp
sample.cpp: In member function 'void Derive<T>::pankaj()':
sample.cpp:14: error: 'entries' was not declared in this scope
sample.cpp: In member function 'void Derive<T>::clear()':
sample.cpp:22: error: 'entries' was not declared in this scope
sample.cpp: In function 'int main()':
sample.cpp:26: error: missing template arguments before 'b1'
sample.cpp:26: error: expected `;' before 'b1'
谢谢!!
最佳答案
必须使用this->foo
来访问模板基类中的成员变量foo
。 You may ask why.
此外,正如老狐狸所解释的那样,在声明变量b1
时必须指定类型T
。
template <class T>
class Base
{
public:
int entries;
};
template <class T>
class Derive : public Base<T *>
{
public:
int j;
void pankaj(){j = this->entries;}
void clear();
};
template <class T> void Derive<T>::clear()
{
int i;
int j=this->entries;
};
int main()
{
Derive<int> b1;
}
关于c++ - C++ 中的继承和模板 : Why doesn't the following piece of code compile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876488/