1

我有这个文件myfuncts.hpp::

#ifndef FUNCTS_
#define FUNCTS_
namespace root {
namespace functs {
template <typename T>
class f1 {
public:
  T r;
  f1();
};
}
}
#endif

我有实现myfuncts.cpp

#include "myfuncts.hpp"
template <typename T>
root::functs::f1<T>::f1() { /* do somethng */ }

然后我有我的主要程序:

#include "impulses.hpp"
int main(int argc, char** argv);
int main(it argc, char** argv) {
  root::functs::f1<double> f();
}

我编译它:

g++ main.cpp functs.cpp

得到了这个:

/tmp/ccrdJEQt.o: 在函数main': main.cpp:(.text+0x53): undefined reference toroot::functs::f1::f1()' collect2: ld 返回 1 退出状态

我究竟做错了什么?

4

1 回答 1

6

您可能想了解最令人烦恼的解析,因为当您这样做时

root::functs::f1<double> f();

您声明f为返回root::functs::f1<double>对象的函数。

您可能还想阅读这个老问题,了解您实际收到undefined reference错误的原因。这是因为头文件没有完全定义类。对于模板类,完整的实现也必须在头文件中。

于 2013-09-03T07:32:29.770 回答