C++中的继承和模板:为什么以下一段代码不编译?
Inheritance and template in C++: Why doesn't the following piece of code compile?
我有一个简单的c ++程序,我无法编译,虽然我试图在谷歌中搜索并尝试阅读模板,继承和向量,但我没有任何线索,我犯了什么错误,任何人都可以帮助我!!以下是代码:
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
。你可能会问为什么。
此外,正如 Old Fox 所解释的那样,在声明变量 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;
}
现场演示在这里
您的主方法有语法错误,请更改为:
int main()
{
Derive<int> b1;
}
你可以把其他类型而不是整数...
在 C++ 中,模板是编译时
相关文章:
- 如何为一段代码启用 -permissive
- 使用Qt Creator在调试模式下编译一段代码
- 防止一段代码在协程中并发执行
- 通过创建单个线程来运行一段代码可加快执行速度
- 有没有一种标准方法来确保一段代码在全局范围内执行
- C++函数 Sleep() 在一段代码之前执行
- C++中的继承和模板:为什么以下一段代码不编译?
- 一段C++代码出现错误"invalid pointer"
- 我必须编写一段代码,基本上执行c++中的strlen()函数,哪里出了问题
- 关于行列式计算的一段代码的问题
- 将两个或多个互斥体应用于一段代码
- 使类使用浮点数和整数(分析一段代码)
- 如何在C++中编写一段代码以查找系统路径上文件的完整路径
- 从第二次调用开始在函数中执行一段代码
- 将一段C++代码封装到Python中
- 解释一段c++代码
- 了解CHIP8模拟器中的一段代码
- 将一段代码从c++转换为c#
- 如何只执行一段代码一次
- 如何对依赖于Asio的一段代码进行单元测试