C++ 为什么在方法或函数名之前和之后使用 const 关键字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16449889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why using the const keyword before and after method or function name?
提问by Vick_Pk
I have the following code in my application. Why do we use the const
keyword with the return type and after the method name?
我的应用程序中有以下代码。为什么我们const
在返回类型和方法名称之后使用关键字?
const T& data() const { return data_; }
回答by stardust
const T& data() const { return data_; }
^^^^^
means it will return a const
reference to T
(here data_
)
意味着它将返回const
对T
(此处data_
)的引用
Class c;
T& t = c.data() // Not allowed.
const T& tc = c.data() // OK.
const T& data() const { return data_; }
^^^^^
means the function will not modify any member variables of the class (unless the member is mutable
).
意味着函数不会修改类的任何成员变量(除非成员是mutable
)。
void Class::data() const {
this->data_ = ...; // is not allowed here since data() is const (unless 'data_' is mutable)
this->anything = ... // Not allowed unless the thing is 'mutable'
}
回答by Collin Dauphinee
The const
(and volatile
) qualifier binds to the left. This means that any time you see const
, it is being applied to the token to the left of it. There is one exception, however; if there's nothing to the left of the const
, it binds to the right, instead. It's important to remember these rules.
的const
(和volatile
)限定符结合到左侧。这意味着任何时候你看到const
,它都会被应用到它左边的标记上。然而,有一个例外;如果 左边没有任何东西const
,它会绑定到右边。记住这些规则很重要。
In your example, the first const
has nothing to the left of it, so it's binding to the right, which is T
. This means that the return type is a reference to a const T
.
在您的示例中,第一个const
左侧没有任何内容,因此它绑定到右侧,即T
. 这意味着返回类型是对 a 的引用const T
。
The second const does have something to the left of it; the function data()
. This means that the const
will bind to the function, making it a const
function.
第二个 const 的左边确实有一些东西;功能data()
。这意味着const
将绑定到函数,使其成为一个const
函数。
In the end, we have a const function returning a reference to a const T.
最后,我们有一个const 函数返回对 const T 的引用。
回答by Ed Heal
The first const
means the function is returning a const T
reference.
第一个const
意味着该函数正在返回一个const T
引用。
The second one says that the method is not changing the state of the object. I.e. the method does not change any member variables.
第二个说该方法不会改变对象的状态。即该方法不会更改任何成员变量。
回答by shivakumar
const T& data() const { return data_; }
const after member function indicates that data is a constant member function and in this member function no data members are modified.
const after member function 表示 data 是一个常量成员函数,并且在这个成员函数中没有修改数据成员。
const return type indicates returning a constant ref to T
const 返回类型表示向 T 返回一个常量 ref