这看起来很简单,但我无法弄清楚出了什么问题。我正在实现 C++ 向量类(仅适用于 int,而不是模板),并且带有迭代器模板或 typedef 的函数在编译时给了我这些错误:
Undefined symbols:
"void vectorInt::assign<int>(int, int)", referenced from:
_main in ccNVdR23.o
"void vectorInt::assign<int*>(int*, int*)", referenced from:
_main in ccNVdR23.o
_main in ccNVdR23.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
源文件的重要部分是:
向量Int.h
#include <cstdlib>
#include <stdexcept>
typedef unsigned int size_type;
class vectorInt {
private:
int* array;
size_type current_size;
size_type current_capacity;
public:
.
.
.
template <class InputIterator>
void assign(InputIterator first, InputIterator last);
void assign(size_type n, const int u);
};
#endif // VECTORINT_H
向量Int.cpp
#include vectorInt.h
.
.
.
template <class InputIterator>
void vectorInt::assign(InputIterator first, InputIterator last) {
clear();
InputIterator it = first;
int count = 0;
while(it++ != last) {
count++;
}
reserve(count);
while(first != last) {
this->push_back(*first++);
}
}
void vectorInt::assign(size_type n, const int u) {
clear();
reserve(n);
for(int i=0; i<(int)n; i++)
push_back(u);
}
主文件
#include <cstdlib>
#include <stdexcept>
#include <iostream>
#include "vectorInt.h"
using namespace std;
int main(int argc, char** argv) {
vectorInt first;
vectorInt second;
vectorInt third;
first.assign(7, 100);
vectorInt::iterator it;
it = first.begin()+1;
second.assign(it, first.end()-1); // the 5 central values of first
int myints[] = {1776,7,4};
third.assign(myints, myints+3); // assigning from array.
return 0;
}
仅供参考:我知道主要方法使用vectorInt::iterator,但这不是问题,因此我没有将它包含在源代码中。