为什么 std::basic_ostream::operator<< 不是常量限定的?

Jay*_* Yi 1 c++ constants ostream c++11

首先,举一个例子来说明我的问题背后的道德:下面的代码将无法编译,因为 std::basic_ostream::operator<< 是const不合格的。(https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-3.4/ostream-source.html显示操作符const不合格。)

我使用 GNU g++ 6.4.0 编译器编译,并启用了 --std=c++11 标志。

#ifndef TEST_H
#define TEST_H
#include<string>
#include<iostream>
using namespace std;
class ChessPiece{
    const string name;
    const int side;
public:
    ChessPiece(const string&,const int);
    void printPiece(const ostream&) const;
};
#endif // TEST_H
Run Code Online (Sandbox Code Playgroud)

...和test.cpp。

#include"test.h"
ChessPiece::ChessPiece(const string& s,const int bw): name{s}, side{bw} {}
void ChessPiece::printPiece(const ostream& S=cout) const{
    S << "a " << (side==1?"white ":"black ") << name << endl;
}
int main(){
    ChessPiece p{string("pawn"),-1}; // a black pawn
    p.printPiece();
}
Run Code Online (Sandbox Code Playgroud)

但是,我不确定为什么首先会发生这些类型的错误,即使 operator<< 在逻辑上与上面的代码一样const。是的,显而易见的答案是“以某种方式operator<<改变了的内部状态std::ostream”。

但是,我知道通过创建成员mutable我们可以更改类的内容,只要const-qualified 函数在逻辑上是const。我也知道std::ostream在调用其operator<<. (如果我写的有错误,请指出。谢谢)

改写,

为什么逻辑上conststd::basic_ostream::operator<< 没有const限定,而不是让它的一些成员可变?

先感谢您。

R S*_*ahu 5

你说:

我也知道std::ostream在调用其operator<<.

这是查看std::ostream. 另一种看待它的方式是它是一个设备接口——一个文件、一个控制台、一个字符串等。如果该接口中的一个成员函数改变了底层设备,那么使该成员函数成为const成员是一种误导功能。

的概念const是概念性的。看看我的一个回答,它稍微探索了这个主题。是的,可以使operator<<函数与const std::stream对象一起工作,但它们不是更有意义。他们正在改变他们为其提供接口的底层设备,并且,IMO,他们最好使用const类型的非对象std::ostream