本文介绍了使用具有重载的<<操作符endl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++

这是试图建立一个模拟输出行为的类,使用< ofstream 运算符,只要能够使用 std :: endl 并写入 string s。该类有一个单一的数据成员, ofstream 指针。该类有两个重载的<< 运算符,一个采用 std :: string 指向一个函数的指针,其参数是 ostream 引用,并返回一个 ostream 引用。这是 std :: endl 的签名,根据。从技术上讲,以下程序使用给定的输入。它能够打印到文件,两行文本由两个 std :: endl 分隔。但是,我希望我的 -string参数重载< 运算符接受 std :: endl 只是,不是只是匹配其签名的东西。我尝试了在参数列表中放置 std :: endl 的各种组合,有和没有 * code>& ,但每个组合都有编译器错误。也欢迎C ++ 11的答案。

This is an attempt to make a class that mimics the output behavior of using the << operator of an ofstream, as far as being able to use std::endl and write strings is concerned. The class has a single data member, the ofstream pointer. The class has two overloaded << operators, one that takes an std::string and another that takes a pointer to a function, whose argument is an ostream reference and returns an ostream reference. That is the signature of std::endl, according to this. Technically, the below program works with the given input. It is able to print to file, two lines of text separated by two std::endls. However, I want my non-string parameter overloaded << operator to accept std::endl only, not something that merely matches its signature. I tried various combinations of placing std::endlin the argument list, with and without * and with and without &, but I got compiler errors for every combination. C++11 answers are also welcome.

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

class TextOut
{
public:
    TextOut(std::ofstream* ofsPar) : ofs(ofsPar) {}
    TextOut& operator<<(std::string s)
    {
        *ofs << s;
        return *this;
    }
    TextOut& operator<<(std::ostream& (*endlPar) (std::ostream& os))
    {
        *ofs << std::endl;
        return *this;
    }
private:
    std::ofstream* ofs;
};

int main()
{
    std::cout << "Enter filename: ";
    std::string filename;
    std::cin >> filename;
    std::ofstream myofstream(filename.c_str());
    TextOut myTextOut(&myofstream);
    myTextOut << "Hello," << std::endl << std::endl << "spacious world.";
    return 0;
}

输出

Hello,

spacious world.


推荐答案

如果我看看我的ostream头文件, :

If I look at my ostream header file I see this for endl:

template<typename _CharT, typename _Traits> inline basic_ostream<_CharT, _Traits>&
  endl(basic_ostream<_CharT, _Traits>& __os)
  {
     return flush(__os.put(__os.widen('\n')));
  }

看起来像是需要继承 basic_ostream 使这项工作。不确定你真的想这样做。

so it looks like you would need to inherit from basic_ostream to make this work. Not sure you really want to do that.

这篇关于使用具有重载的&lt;&lt;操作符endl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:23