undefined reference to c++ class constructor [duplicate]

五迷三道 提交于 2019-12-24 03:08:20

问题


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

 #ifndef MYCOUNTER_H
 #define MYCOUNTER_H

 template<class T>
 class MyCounter
 {
   public:
      MyCounter();
 };

 #endif // MYCOUNTER_H

mycounter.cpp

   #include "mycounter.h"
   #include <iostream>


  template<class T>
  MyCounter<T>:: MyCounter()
 {
  std::cout<<"somthing...";
}

回答1:


If you have a template, the entire implementation should be in the header file.

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



来源:https://stackoverflow.com/questions/17391770/undefined-reference-to-c-class-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!