了解如何阅读 C++ 代码的“常量”

Understanding how read the `const`ness of c++ code

在我尝试自学 C++ 时,我希望在如何阅读 expression/function 等的常量方面得到一些帮助。例如,下面的代码:

const screen &display(std::ostream &output) const {
    do_display(output); return *this;
}

在上面的代码中。函数 display 中有两个 const 声明。在 "English" 中,如何正确阅读?示例:第一个 const 是要引用的 const 还是要键入 screenconst?等等,以及当引用是 const 时 const-ness mean/imply 究竟做了什么等等。我已经尝试阅读它但在这一点上仍然有点混乱。

随时指向 YouTube 视频或其他参考资料 material。希望material说的很清楚。

英文意思是:

display() 是其 class(这是第二个 const 关键字)的常量方法,它引用 std::ostream class 实例作为其参数,returns 对 screen class.

的常量(这是第一个 const 关键字)实例的引用

一个const引用表示这个引用不能用来修改被引用的对象。您只能使用引用来访问但不能更改 class 的成员,或调用 class 的 const 方法(如 display() 是const 自己的方法 class).

我一直发现最简单的记忆方法是:

const applies to whatever is to the left of it, unless there isn't anything to the left of it, in which case it applies to whatever is to the right of it.

因此,您有一个 const method returns 一个 constscreen 的引用。

A const 引用意味着您不能修改引用的对象。 const 方法意味着该方法不会修改被调用的对象(该方法中的 this 指针将指向 const 对象)。

你是从右到左读的。 您有一个常量方法,该方法 returns 对常量屏幕的引用。

返回常量引用意味着您无法修改返回的内容。 如果调用该方法并将其分配给某个变量,则该变量必须使用 const 关键字。唯一的例外是,如果您将返回的引用从方法转换为不常量的东西。

这里有一个有用的link,可以了解有关从右到左规则的更多详细信息: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html

其实是加州大学圣地亚哥分校的一位教授写的(而且他很不错)。

方法右侧的 const 仅表示您不能修改函数内的任何实例变量(大部分情况下)。它还有更多内容,但有关更多详细信息,请参阅: Meaning of "const" last in a C++ method declaration?

从右到左阅读。

int const & foo() const

const 方法,其中 returns 一个...

int const & foo() const

参考...

int const & foo() const

const int.

const 可以在 int 的任一侧。您可以将其读作 "constant integer" 或 "integer which is constant".