ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – typedef和template的未定义符号?

2019-09-02 13:08:10  阅读:281  来源: 互联网

标签:c templates typedef undefined-symbol


参见英文答案 > Why can templates only be implemented in the header file?                                    16个
这看起来很简单,但我无法弄清楚出了什么问题.我正在实现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,但这不是问题,因此我没有在源代码中包含它.

解决方法:

模板代码获得2阶段编译.第一阶段仅包括基本语法检查.第二个阶段依赖于类型T,从编译器获得完整的编译.由于您的代码(实现)是在CPP文件中,它只会获得第一阶段编译,因此它不会包含在翻译单元中 – 不会生成任何目标文件.

对于模板,您必须允许编译器编译整个代码.同样,您需要将整个实现仅放在头文件中.您也可以在类声明后立即#include相应的CPP文件.

标签:c,templates,typedef,undefined-symbol
来源: https://codeday.me/bug/20190902/1791210.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有