为什么我们应该在c ++中使用const进行运算符重载? [英] Why we should use const for operator overloading in c++ ?

查看:96
本文介绍了为什么我们应该在c ++中使用const进行运算符重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



明天我参加考试,我正在读书..



当我们在c ++中使用运算符重载时,我已经认识到,大多数示例都是const?

这是什么意思,我可以记住考试,但是,我想知道那是什么逻辑..



感谢您的回答:)

Hi guys,

Tomorrow I have an exam, i am studying now..

When we use operator overloading in c++, i ve recognized that, most of examples inluceds const ?
What is that mean, i can memorize for exam but, i want to learn what is that logic..

Thanks for answers :)

推荐答案

Const只是意味着你向你赢得的编译器承诺' t修改值。然后编译器可以应用优化来使一切工作更快。
Const just means that you promise to the compiler that you won't modify the value. The compiler can then apply optimizations to make everything work faster.


首先,让我祝你明天考试好运。



其次,在运算符重载中添加const是安全编程实践的一部分,因为它保护您传递给重载函数的变量,这些变量不会被您的程序或某些/其他人意外更改。



一个很好的例子是运算符重载=。



当你将参数传递给重载函数,你应该通过向该变量添加const来保护程序不改变传递给重载函数的值。
First off, let me wish you good luck for your tomorrow exam.

Second, adding const in operator overloading is a part of safe programming practice, since it protects variables that you pass to the overloading function, WHICH ARE NOT INTENDED TO CHANGE, of being accidentally changed by your program or by something/someone else.

A good example of this is overloading of operator =.

When you pass your parameters to the overloading function, you should protect the program from changing the value passed to the overloading function, by adding const to that variable.


这篇关于为什么我们应该在c ++中使用const进行运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆