【问题标题】:C++ operator<< overloading ofstream using templates [duplicate]C ++运算符<<使用模板重载流[重复]
【发布时间】:2014-11-01 14:42:22
【问题描述】:

我正在尝试重载 operatorCExportFunctions 项目中,我可以log &lt;&lt; "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 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()";
}

【问题讨论】:

    标签: c++ templates operator-overloading dllexport


    【解决方案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&lt;&lt;(std::ofstream&amp;, const char*)... 这不涉及打开文件。我想你的意思是:

    log << "Entered processMessage()";
    

    【讨论】:

    • 谢谢。我做不到log &lt;&lt; "Entered processMessage()"。它说 Error: no operator " 我必须导出模板才能在另一个项目的类中使用吗?也许我没有说清楚。 CCallMethods() 是项目 B 中的一个方法。
    • 您的模板化操作符是否在您的 .cpp 文件中定义?如果是这样,那么它就是不可见的。您必须将其移至标题。
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2012-11-14
    • 2021-09-19
    • 2016-02-03
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多