c++ - 如何初始化对 std::ofstream 的静态引用?

标签 c++ reference static ofstream

我有一个公共(public)成员的类 Cl

static std::ofstream &_rout;

在主文件中

ofstream out("output.txt");
ofstream& Cl::_rout(out);

但是我有一个编译错误:非法定义或重定义。 我该如何纠正它?

最佳答案

试试这个。

Logger.h

#include <string>
#include <fstream>
#include <iostream>

using namespace std;

class Logger{

    public:
            static void open( const string & logFile);
            static void close();
            // write message
            static void write( const string & message);

    private:
          Logger();
          ofstream fileStream;
          //Logger instance (singleton)
          static Logger instance;
};

Logger.cpp

#include "Logger.h"

Logger Logger::instance;

Logger::Logger(){}

void Logger::open( const string& logFile){
   instance.fileStream.open(logFile.c_str());
}
void Logger::close(){
    instance.fileStream.close();

} 
void Logger::write(const string& message){
    ostream& stream =  instance.fileStream ;
    stream << message<< endl;
}

main.cpp

#include "Salida/Logger.h"
int main(){
    Logger::open(path);
    Logger::write("text");
    Logger::close();
    return 0;

关于c++ - 如何初始化对 std::ofstream 的静态引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194253/

相关文章:

c# - 有一种方法可以在 C# 中使用可变参数按引用传递吗?

c++ - 在 C++ 中使用静态映射缓存数据的推荐方法是什么

c++ - static constexpr 函数与全局函数不同?

c++ - 在不打开文件的情况下将数据存储在 ofstream 中

c++ - 如何将 const char* 从一个函数转移到另一个函数?

c++ - 我在哪里可以找到 SVN .lib 文件?

c++ - 使用 libcurl : it does not appear to get the entire page 时出现问题

c++ - 返回对原始参数的引用

c++ - 引用二维 vector 中的元素 (c++)

c - 翻译单元中 `static` 定义和 `extern declaration` 的顺序