This question already has answers here: Operator overloading on class templates (5个答案) 5年前关闭。 我正在尝试重载operator CExportFunctions 项目中,我能够log << "xxx"。但是,当我尝试在另一个项目( CCallMethods )中执行相同操作时,无法写入该文件。编译还可以。没有错误。但是Entered processMessage()没有写到文件中。有人可以帮忙吗?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 filetemplate<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 dialogvoid CExportFunctions::saveScenario(){ CExportFunctions log; log << "Entered saveScenario()"; ...}Project B - CCallMethods.cpp:#include "CExportFunctions.h"void CCallMethods::processMessage(){ ... CExportFunctions log; log.stream << "Entered processMessage()";} (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您正在调用不同的函数。在您的保存方案中://! save scenario dialogvoid 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()"; (adsbygoogle = window.adsbygoogle || []).push({}); 08-16 01:06