gpt4 book ai didi

c++ - C++中的继承和模板 : Why doesn't the following piece of code compile?

转载 作者:搜寻专家 更新时间:2023-10-31 01:40:22 25 4
gpt4 key购买 nike

我有一个简单的 C++ 程序,我无法编译它,尽管我尝试在谷歌中搜索并尝试阅读有关模板、继承和 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 来访问模板基类中的成员变量fooYou 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;
}

live demo here

关于c++ - C++中的继承和模板 : Why doesn't the following piece of code compile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com