C++ C+中的链接错误+;模板

C++ C+中的链接错误+;模板,c++,templates,linker,C++,Templates,Linker,我需要生成一个简单的记录器(没有第三方libs),需要链接到dll。因此我生成了一个类,用他的一些类方法得到了模板,代码编译得很好,但我得到了链接器错误。我使用MS VS 2008和gcc-4进行编译。代码是: Log.h类: class MiniLogger { private: std::ofstream mOutPutFile; protected: void write (std::string const& text); public: ~MiniLogger

我需要生成一个简单的记录器(没有第三方libs),需要链接到dll。因此我生成了一个类,用他的一些类方法得到了模板,代码编译得很好,但我得到了链接器错误。我使用MS VS 2008和gcc-4进行编译。代码是:

Log.h类:

class MiniLogger
{
private:
   std::ofstream mOutPutFile;
protected:
   void write (std::string const& text);
public:
   ~MiniLogger();
   MiniLogger( std::string const& lName) throw(FileError);
   static MiniLogger* getInstance(std::string const & fName);
   static void destoryInstance(MiniLogger*);

  template<class T>
  MiniLogger& operator<<(T & data);
  MiniLogger& operator<<(std::ostream& (*func)(std::ostream&) );

};


MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&))
{

   //mOutPutFile << out;
   return *this;
}
template<class T>
MiniLogger& MiniLogger::operator<< (T  & data)
{
 //Just try with out calling other method
// write(data);
   return *this;
}
class微型记录器
{
私人:
std::of流moutput文件;
受保护的:
无效写入(标准::字符串常量和文本);
公众:
~MiniLogger();
微型记录器(std::string const&lName)抛出(FileError);
静态迷你记录器*getInstance(std::string const&fName);
静态void destoryInstance(MiniLogger*);
模板

MiniLogger&operator您已经在头文件中定义了一个函数。由于该头文件包含在多个翻译单元(即main.cpp和log.cpp)中,因此您已经多次定义了该函数。(请参阅。)

要么在头文件中声明函数
inline
并定义它,要么在头文件中声明函数
extern
,并在一个源文件中定义它


所讨论的函数是:
MiniLogger&MiniLogger::operator请注意,模板代码工作正常;您的链接器错误在非模板代码中。
#include "log.h"

int main()
{


    MiniLogger &a=*(MiniLogger::getInstance("text.txt"));

    a << "text" << std::endl;


return 0;
}
@ubu11-10-64b-01:~/cplus/template$ g++ main.cpp log.cpp
/tmp/cccMdSBI.o: In function `MiniLogger::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))':
log.cpp:(.text+0x0): multiple definition of `MiniLogger::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
/tmp/ccj3dfhR.o:main.cpp:(.text+0x0): first defined here
// Log.h
inline
MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&))
{
 //mOutPutFile << out;
 return *this;
}
// Log.h
extern
MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&));

// Log.cpp
MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&))
{
 //mOutPutFile << out;
 return *this;

}