gpt4 book ai didi

c++ - 试图写 std :out and file at the same time

转载 作者:太空狗 更新时间:2023-10-29 19:44:09 25 4
gpt4 key购买 nike

我试图通过重载 ofstream 在 C++ 中同时写入文件和标准输出

测试.h

 #pragma once 

#include <iostream>

using std::ofstream;

class OutputAndConsole:public ofstream
{
public:
std::string fileName;
OutputAndConsole(const std::string& fileName):ofstream(fileName),fileName(fileName){
};
template <typename T>
OutputAndConsole& operator<<(T var);
};


template <typename T>
OutputAndConsole& OutputAndConsole::operator<<(T var)
{
std::cout << var;
ofstream::operator << (var);
return (*this);
};

测试.cpp

  OutputAndConsole file("output.txt");
file << "test" ;

文件中的输出是

01400930

但是在控制台是

test

我调试了它看起来正在进入的代码

_Myt& __CLR_OR_THIS_CALL operator<<(const void *_Val)

我做错了什么?

最佳答案

我不打算评论为什么您的方法不起作用,主要是因为无法对其进行修补以使其正常工作。主要问题是您不能使用您的流并将其传递给需要 std::ostream& 的东西并且仍然写入两个流。然而,有一个相对简单但不一定明显的方法来实现你真正想要的:你将派生一个新的流缓冲区,即派生自 std::streambuf 的类,并覆盖它的 overflow()sync() 函数。这是一个简单演示的完整代码:

#include <streambuf>

struct teebuf
: std::streambuf
{
std::streambuf* sb1_;
std::streambuf* sb2_;

teebuf(std::streambuf* sb1, std::streambuf* sb2)
: sb1_(sb1), sb2_(sb2) {
}
int overflow(int c) {
typedef std::streambuf::traits_type traits;
bool rc(true);
if (!traits::eq_int_type(traits::eof(), c)) {
traits::eq_int_type(this->sb1_->sputc(c), traits::eof())
&& (rc = false);
traits::eq_int_type(this->sb2_->sputc(c), traits::eof())
&& (rc = false);
}
return rc? traits::not_eof(c): traits::eof();
}
int sync() {
bool rc(true);
this->sb1_->pubsync() != -1 || (rc = false);
this->sb2_->pubsync() != -1 || (rc = false);
return rc? 0: -1;
}
};

#include <fstream>
#include <iostream>

int main()
{
std::ofstream fout("tee.txt");
teebuf sbuf(fout.rdbuf(), std::cout.rdbuf());
std::ostream out(&sbuf);
out << "hello, world!\n";
}

显然,可以很好地打包 tee-stream 的创建,但它看起来如何并不重要。重要的是,可以为 IOStreams 创建自定义目标(或源),并且它不涉及任何从 std::ostream 继承的尝试。从 std::ostream(或 std::istream)继承的唯一原因是使用自定义流缓冲区更容易初始化流。

关于c++ - 试图写 std :out and file at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13665090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com