2014-11-01 86 views
1

我想超载运算符< < ostream执行写入日志文件机制。在CExportFunctions项目中,我能够log << "xxx"。但是,当我尝试在另一个项目中执行相同操作时(CCallMethods),我无法写入该文件。汇编没问题。没有错误。但Entered processMessage()没有写入文件。任何人都可以帮忙吗?C++运算符<<使用模板的流的超载

Project A - CExportFunctions.h: 
#ifdef DLLDIR_EX 
    #define DLLDIR __declspec(dllexport) // export DLL information 
#else 
    #define DLLDIR __declspec(dllimport) // import DLL information 
#endif 

... 

class DLLDIR CExportFunctions 
{ 
public: 
    ... 

    ofstream stream; 
}; 

Project A - CExportFunctions.cpp: 

#include "CExportFunctions.h" 

... 

//! write to log file 
template<typename T> CExportFunctions& operator<<(CExportFunctions& stream, T val) 
{ 
    ... 

    stream.stream.open("D:/Logger/logs.txt", ios::out | ios::app); 
    stream.stream << << val << std::endl; 
    stream.stream.close(); 

    return stream; 
} 

//! save scenario dialog 
void CExportFunctions::saveScenario() 
{ 
    CExportFunctions log; 
    log << "Entered saveScenario()"; 

    ... 
} 

Project B - CCallMethods.cpp: 

#include "CExportFunctions.h" 

void CCallMethods::processMessage() 
{ 
    ... 

    CExportFunctions log; 
    log.stream << "Entered processMessage()"; 
} 

回答

1

你在调用不同的函数。在您保存场景:

//! save scenario dialog 
void CExportFunctions::saveScenario() 
{ 
    CExportFunctions log; 
    log << "Entered saveScenario()"; 

    ... 
} 

你实际上是在呼唤你的

template<typename T> CExportFunctions& operator<<(CExportFunctions& stream, T val) 

但是这第二个:

void CCallMethods::processMessage() 
{ 
    ... 

    CExportFunctions log; 
    log.stream << "Entered processMessage()"; 
} 

你打电话operator<<(std::ofstream&, const char*) ...这不涉及打开文件。我认为你的意思是:

log << "Entered processMessage()"; 
+0

谢谢。我不能做'log <<“输入的processMessage()”'。它说**错误:没有操作符“<<”匹配这些操作数**我是否必须导出要在另一个项目类中使用的模板?也许我没有说清楚。 'CCallMethods()'是一个来自Project B的方法。 – Wallace 2014-11-01 15:20:43

+0

您的模板化操作符是否在.cpp文件中定义?如果是这样,那就不可见了。您必须将其移至标题。 – Barry 2014-11-01 15:33:38