const关键字在编程中有什么好处?
可能的重复:
向我推销 const 正确性
我很想知道答案。 [到“const
关键字在编程中有什么好处?”]
Possible Duplicate:
Sell me on using const correctness
I'm eager to know the answer. [to "What is the benefit of const
keyword in programming?"]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
const
表示分配给变量的值不能更改。如果您尝试更改该值,您应该会收到编译器错误。const
indicates that the value assigned to the variable cannot change. If you try to change the value you should get a compiler error.const
关键字可以声明只读变量。在方法中使用 const 参数告诉您该方法不会更改参数。
const 方法告诉您该方法不会更改类的成员变量(但可以更改标记为 可变)
您还可以声明
const
指针,更好地描述此处The
const
keyword can declare a read only variable.Using
const
parameters to a method tells you the method will not change the parameter.A
const
method tells you that the method will not alter a class's member variables (but can change member variables marked as mutable)You can also declare
const
pointers, better described here将变量指定为 const 表明该变量的值在初始赋值后不应更改。这允许编译器在编译时执行额外的测试(验证您的代码)。
例如,如果 const 函数更改对象中的(非可变)成员,编译器将产生错误。
Specifying a variable as const states that the variable's value should never change after the initial assignment. This allows the compiler to perform additional tests at compilation (validating your code).
For example, if a const function changes a (non-mutable) member in an object, the compiler will yield an error.
好处:您可以获得更多的编译时检查,以确保您没有更改不应更改的数据。
成本:你必须在任何地方使用它。如果你需要的话,你可以摆脱它,从而抵消它的好处。
正确使用指针可能会很棘手。指针本身是常量,还是它引用的数据?这也是我见过的最常见的用法:你想指向不可变的内存。
Benefit: You get more compile time checks to ensure that you're not changing data that shouldn't be changed.
Cost: You have to use it everywhere. If you need to, you can cast your way out of it, nullifying the benefits.
Getting usage right can be tricky with pointers. Is the pointer itself const, or the data it refers to? This is also the most common usage I've seen: you want to point to immutable memory.