c++中使用模板的问题
Problem using templates in C++
我第一次在c++中使用模板,当我试图编译时遇到了一个问题。基本上是尝试创建我自己的基本数组列表:
. hpp:
#ifndef ARRAYLIST_HPP_
#define ARRAYLIST_HPP_
template <class T>
class ArrayList
{
private:
int current, top ;
T * al ;
public:
ArrayList() ; // default constructor is the only one
};
#endif /* ARRAYLIST_HPP_ */
. cpp:
#include "ArrayList.hpp"
using namespace std ;
//template <class T>
//void memoryAllocator( T * p, int * n ) ; // private helper functions headers
template <class T>
ArrayList<T>::ArrayList()
{
current = 0 ;
top = 10 ;
al = new T[top] ;
}
主:#include "ArrayList.hpp"
int main()
{
ArrayList<int> test ;
}
当我尝试在没有main的情况下构建时,它编译得很好,但是,一旦我尝试在main中使用它,我就会得到以下错误:
Undefined symbols for architecture x86_64:
"ArrayList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::ArrayList()", referenced from:
_main in Website.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [APProject2] Error 1
任何想法,可能是什么问题将不胜感激!
干杯!
模板需要在头文件中声明和。
Also:我不认为这是真正的错误。它提到了ArrayList<std::string>
的实例化,我在任何地方都看不到。
这个常见问题解答解释了为什么。
您需要在.hpp文件中包含该实现。编译器需要在编译时知道T来生成专门化。
你不能把模板化的代码放到一个单独的。cpp文件中…你的构造函数应该在ArrayList头文件中。关键是,只有当main()
被编译时,编译器才意识到它需要实例化ArrayList以及T将采用什么类型,因此它需要有可用的代码来进行实例化....
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题