“const”如何表示? C 和 C++ 有何不同?
C 和 C++ 中变量的 const 限定有何不同?
“引发此问题的是以下答案:https://stackoverflow.com/questions/4024318# 4024417 他说 const “just” 在 C 中意味着只读。我认为这就是 const 的全部含义,无论是 C 还是 C++,他是什么意思?”
How does the const qualification on variables differ in C and C++?
from: Does "const" just mean read-only or something more?
"What prompted this question was this answer: https://stackoverflow.com/questions/4024318#4024417 where he states const "just" means read-only in C. I thought that's all const meant, regardless of whether it was C or C++. What does he mean?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C 中的
const
不能用于构建常量表达式。例如:
在 C 中不起作用,因为 case 标签不会简化为整数常量。
const
in C cannot be used to build constant expressions.For example :
doesn't work in C because case label does not reduce to an integer constant.
const
表示您承诺不会改变变量。仍然可以改变。没有方法
A::*
可以更改a
,但main
可以。 C 和 C++ 之间有很多相同之处。C++ 确实有一些(有限的)绕过
const
的方法,这些方法应该阻止程序员不恰当地丢弃const
。上这样的课。
cachedComputation
隐式表示this->cachedComputation
。请记住这一点。a2.getValue()
是非法的,因为在const A a2
上调用非const
方法。一个可以抛弃const
-ness…第二种是首选,因为编译器将检查是否仅转换
const
-ness,而不是其他。然而,这仍然不理想。相反,应该向类中添加一个新方法。现在有一个 const 方法,所以 a2.getValue() 就可以了。但是,尾随的 const 意味着该方法被赋予一个 const A *this 指针,而不是像通常那样的 A *this 指针,使得 < code>this->cachedComputation 一个无法改变的
const int &
。const_cast 可以在方法内部应用,但更好的方法是更改该成员的声明。
现在,即使使用 const A *this,
this->cachedComputation
也可以在不进行转换的情况下进行变异。const
means that you promise not to mutate the variable. It could still be changed.No method
A::*
may changea
, butmain
can. That much is identical between C and C++.What C++ does have are a couple (limited) ways to bypass
const
, which are supposed to discourage programmers from discardingconst
inappropriately.Take a class like this.
cachedComputation
implicitly meansthis->cachedComputation
. Keep this in mind.a2.getValue()
is illegal, because a non-const
method is being called on aconst A a2
. One could cast away theconst
-ness…The second is preferred, because the compiler will check that only the
const
-ness is being casted, nothing else. However, this is still not ideal. Instead, there should be a new method added to the class.Now there is a
const
method, soa2.getValue()
is fine. However, the trailingconst
means that the method is given aconst A *this
pointer, not anA *this
pointer like usual, makingthis->cachedComputation
aconst int &
that cannot be mutated.const_cast
could be applied inside the method, but better would be to change this one member's declaration.Now, even with a
const A *this
,this->cachedComputation
can be mutated without casting.