链接步骤中未定义C++引用错误

Undefined reference error in C++ Link step

本文关键字:C++ 引用 错误 未定义 链接      更新时间:2023-10-16

我正在尝试在C++中制作一个简单的边界检查数组。我在头文件中声明了一个类,并在单独的源文件中定义了该类。编译步骤运行良好,但是当我尝试链接对象时,出现以下错误:

$ g++.exe -o a.exe srcmain.o srcarray.o
srcmain.o: In function `main':
../src/main.cpp:7: undefined reference to `Array<int>::Array(int)'
../src/main.cpp:9: undefined reference to `Array<int>::operator[](int)'
../src/main.cpp:10: undefined reference t o `Array<int>::operator[](int)'
../src/main.cpp:11: undefined reference t o `Array<int>::operator[](int)'
../src/main.cpp:13: undefined reference t o `Array<int>::operator[](int)'
../src/main.cpp:7: undefined reference to `Array<int>::~Array()'
../src/main.cpp:7: undefined reference to `Array<int>::~Array()'
collect2.exe: error: ld returned 1 exit status

主.cpp

#include <iostream>
#include "array.hpp"
using namespace std;
int main() {
  Array<int> x(10); // compiler error
  x[0] = 1; // compiler error
  x[1] = 2; // compiler error
  x[2] = 3; // compiler error
  cout << x[1] << endl; // compiler error
  return 0;
}

阵列.hpp

#ifndef ARRAY_HPP_
#define ARRAY_HPP_
template <class T>
class Array{
private:
  T* array;
  int length_;
public:
  Array(int);
  ~Array();
  int Length();
  int& operator[](int);
};
#endif /* ARRAY_HPP_ */

阵列.cpp

#include "array.hpp"
template <class T>
Array<T>::Array(int size) {
  length_ = size;
  array = new T[size];
}
template <class T>
Array<T>::~Array() {
  delete[] array;
}
template <class T>
int Array<T>::Length() {
  return length_;
}
template <class T>
int& Array<T>::operator[](const int index) {
  if (index < 0 || index >= length_) {
    throw 100;
  }
  return array[index];
}

模板类成员的定义应位于定义模板类本身的同一标头中。

模板类的所有代码都必须在头文件中,否则它们只能用于在 cpp 文件中显式实例化的类型。