【问题标题】:Const member function Changing Object Data Memberconst 成员函数更改对象数据成员
【发布时间】:2021-05-20 14:38:57
【问题描述】:

您好,我正在读一本书,并且在 const 成员函数部分有一个疑问。代码如下:

class Screen {
public:
    // display overloaded on whether the object is const or not
    Screen &display(std::ostream &os)
        { do_display(os); return *this; }
    const Screen &display(std::ostream &os) const
        { do_display(os); return *this; }
private:
    // function to do the work of displaying a Screen
    void do_display(std::ostream &os) const
    {os<<contents;}

};

我的问题在最后一行,写的是 os 但由于 do_display 是一个 const 成员函数,它如何修改 std::string 类型的数据成员内容? contents 是 Screen 类的私有数据成员,正如您在示例中看到的那样,内容已在 const 成员函数中更改。这是怎么回事? const 不是意味着我们不能更改类的任何数据成员吗?书里有错字还是我遗漏了什么?作为参考,我附上了我突出显示这部分的书中的屏幕截图。

【问题讨论】:

  • 该声明来自contentsos 被“修改”,而不是内容。
  • “如您在示例中看到的内容已更改...”,不,我没有看到它。

标签: c++ c++11 constants ostream


【解决方案1】:

由于os 不是您班级的成员,所以这不是问题。类的成员在该语句中没有改变。

contents 成员只能读取,不能修改。

【讨论】:

  • 那么这是否意味着数据成员contents的内容已经写入os对象了?
  • 这是应该发生的,是的。
  • 好吧,我反过来读了。谢谢
  • 另一种方法是使用 InputStream 时。更容易记住:数据向操作符的方向移动,即 os > data 从 is 读取到 data 中。
  • 我正要问同样的问题。因此,如果我理解正确,那么我们将无法在 const 成员函数中写入 is&gt;&gt;contents,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 2017-10-11
  • 2016-08-17
  • 2011-11-15
相关资源
最近更新 更多