wocan23 2019-09-24 15:54 采纳率: 100%
浏览 548
已采纳

c++简单类模板报错问题

环境:clion mac

TmpOperator.h

#ifndef TEXT_TMPOPERATOR_H
#define TEXT_TMPOPERATOR_H

template <typename T>
class TmpOperator {
public:
     T& test1(T& t);
};


#endif //TEXT_TMPOPERATOR_H

TmpOperator.cpp

#include "TmpOperator.h"

template<typename T> T& TmpOperator<T>::test1(T& t) {
    return t;
}

main.cpp

#include <iostream>
using namespace std;
#include "TmpOperator.h"
int main() {

    TmpOperator<int> tmpOperator;
    int a = 1;
    int b = tmpOperator.test1(a);
    cout << b << endl;
}

看着代码没啥毛病啊,为啥报错啊

Scanning dependencies of target Text
[ 33%] Building CXX object CMakeFiles/Text.dir/main.cpp.o
[ 33%] Building CXX object CMakeFiles/Text.dir/TmpOperator.cpp.o
[ 50%] Linking CXX executable Text
Undefined symbols for architecture x86_64:
  "TmpOperator<int>::test1(int&)", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [Text] Error 1
make[2]: *** [CMakeFiles/Text.dir/all] Error 2
make[1]: *** [CMakeFiles/Text.dir/rule] Error 2
make: *** [Text] Error 2
  • 写回答

2条回答

  • qtchen_1988 2019-09-24 16:15
    关注

    C++要求模板的声明和实现对引用者必须都可见,模板的声明和实现要放到一个文件里,都写在.h文件里

    你可以把

    template<typename T> T& TmpOperator<T>::test1(T& t) {
        return t;
    }
    

    移到头文件(.h) 或者 移到main.cpp

    或者在main.cpp 添加#include "TmpOperator.cpp"
    这种很少用,在这我只是说明,要让调用者可见

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值