为什么使用const关键字前后的方法或函数名? [英] Why using the const keyword before and after method or function name?
本文介绍了为什么使用const关键字前后的方法或函数名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的应用程序中有以下代码。为什么我们对返回类型和方法名后使用 const
关键字?
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 T& data() const { return data_; }
推荐答案
const T& data() const { return data_; }
^^^^^
表示将返回 const (
) $
b $ b
means it will return a const
reference to T
(here data_
)
Class c;
T& t = c.data() // Not allowed.
const T& tc = c.func() // OK.
const T& data() const { return data_; }
^^^^^
表示函数不会修改类(除非成员 mutable
)。
means the function will not modify any member variables of the class (unless the member is 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'
}
这篇关于为什么使用const关键字前后的方法或函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文