【问题标题】:Undefined symbols for typedef and template? [duplicate]typedef和模板的未定义符号? [复制]
【发布时间】:2012-02-13 16:54:13
【问题描述】:

这看起来很简单,但我不知道出了什么问题。我正在实现 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

源文件的重要部分是:

vectorInt.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

vectorInt.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);
}

main.cpp

#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;
}

仅供参考:我知道 main 方法使用 vectorInt::iterator,但这不是问题,因此我没有将它包含在源代码中。

【问题讨论】:

    标签: c++ templates typedef undefined-symbol


    【解决方案1】:

    模板代码得到阶段编译。第一阶段仅包括基本的语法检查。第二阶段依赖于类型 T,从编译器获得完整编译。类/函数将根据类型T 进行实例化,第二阶段编译将针对该类型运行。

    由于您的代码(实现)在.cpp 文件中,它只会进行第一阶段编译,因此不会包含在翻译单元中 - 不会生成目标文件。

    对于模板,您必须允许编译器编译整个代码。同样,您只需将整个实现放在头文件中。你也可以在类声明之后#include各自的.cpp文件。

    【讨论】:

    • 啊,我明白了。我继续将实现添加到头文件中,错误消失了,但现在很难区分这两种方法,我相信这是因为我没有将类作为模板,而只是整数。再次感谢。
    【解决方案2】:

    将分配函数的代码放在头文件(vectorint.h)中,应该没问题。模板的代码需要在实例化时可见,在您调用 assign 函数的情况下。

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 2011-09-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多