简体   繁体   English

关于std :: ostream构造函数

[英]About std::ostream constructor

I want to use std::ostream like this: 我想像这样使用std::ostream

int main()
{
    std::ostream os;
    os << "something ..." << std::endl;
    return 0;
}

There's an error said that the ostream constructor is protected: 有一个错误说ostream构造函数受到保护:

error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; 错误:'std :: basic_ostream <_CharT,_Traits> :: basic_ostream()[with _CharT = char; _Traits = std::char_traits]' is protected. _Traits = std :: char_traits]'受到保护。

But I remember operator<< could be overloaded like this: 但我记得operator<<可能像这样重载:

// In a class. 
friend std::ostream & operator<<(std::ostream& out, const String & s) {
    out << s.m_s;
    return out;
}

Any advice on why my code doesn't work? 关于为什么我的代码不起作用的任何建议?

The std::ostream , the std::istream or the std::iostream are base classes of stream types (eg std::stringstream , std::fstream , etc.) in the Standard Library . std::ostreamstd::istreamstd::iostream标准库中流类型的基类(例如std::stringstreamstd::fstream等)。 These classes are protected against instantiation, you can instantiate their derived classes only. 这些类受实例化保护,您只能实例化其派生类。 The error message 错误消息

error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; 错误:'std :: basic_ostream <_CharT,_Traits> :: basic_ostream()[with _CharT = char; _Traits = std::char_traits]' is protected _Traits = std :: char_traits]'受到保护

tells you the same. 告诉你同样的事情。

Your second example is valid because you can use references to the base class of derived classes. 您的第二个示例是有效的,因为您可以使用对派生类的基类的引用。 In this case no constructor is called, a reference only refers to an existing object. 在这种情况下,不会调用构造函数,引用仅引用现有对象。 Here is an example how can use std::ostream& to the std::cout : 这是一个如何使用std::ostream&std::cout的示例:

#include <iostream>

int main() {
    std::ostream& os = std::cout;
    os << "something ..." << std::endl;
}

The reason behind using std::ostream& in overload of operator<< is that you may don't want to overload the the mentioned operator for all individual stream types, but only for the common base class of them which has the << functionality. operator<<重载中使用std::ostream&的原因是你可能不希望为所有单独的流类型重载所提到的运算符,而只是为具有<<功能的它们的公共基类重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM