对c ++类构造函数的未定义引用 [英] undefined reference to c++ class constructor
问题描述
我正在使用Qt5 Creator,所有文件都包含在项目中 (使用"IDE"向导创建"MyCounter"类) 我将代码简化为这一段, 而当我编译并运行时:
i am using Qt5 creator , all the files are included in the project (the class "MyCounter" is created using the IDE wizard) i reduced my code to this one, and when i compile and run:
undefined reference to MyCounter<int>::MyCounter()
main.cpp
#include <QCoreApplication>
#include"mycounter.h" //if include "mycounter.cpp" instead of "mycounter.h" works fine
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyCounter<int> x;
return a.exec();
}
mycounter.h
mycounter.h
#ifndef MYCOUNTER_H
#define MYCOUNTER_H
template<class T>
class MyCounter
{
public:
MyCounter();
};
#endif // MYCOUNTER_H
mycounter.cpp
mycounter.cpp
#include "mycounter.h"
#include <iostream>
template<class T>
MyCounter<T>:: MyCounter()
{
std::cout<<"somthing...";
}
推荐答案
如果您有模板,则整个实现应在头文件中.
您不能(明智地)具有单独实现的模板类和功能(好吧,您 可以在.cpp文件中分别实例化所有专业化功能,但是为什么?毕竟,您不可能考虑每一个可能的专业化,因此这样做毫无意义...)
You can't (sensibly) have template classes and functions implemented separately (well, you can instantiate all of the specializations separately in the .cpp file, but why would you do that? After all, you cannot possibly think about every possible specialization, so there's no point in doing that...)
这篇关于对c ++类构造函数的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!