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限定,而不是让它的一些成员可变?
先感谢您。
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |