c++中使用模板的问题

Problem using templates in C++

本文关键字:问题 c++      更新时间:2023-10-16

我第一次在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将采用什么类型,因此它需要有可用的代码来进行实例化....