2014-11-01 73 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