C ++ const关键字 - 自由使用? [英] C++ const keyword - use liberally?

查看:145
本文介绍了C ++ const关键字 - 自由使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下C ++函数中:

In the following C++ functions:

void MyFunction(int age, House &purchased_house)
{
    ...
}


void MyFunction(const int age, House &purchased_house)
{
    ...
}

哪个更好?

在两者中,'age'是通过值传递的。我想知道如果'const'关键字是必要的:对我来说似乎多余,但也有帮助(作为一个额外的指示变量不会改变)。

In both, 'age' is passed by value. I am wondering if the 'const' keyword is necessary: It seems redundant to me, but also helpful (as an extra indication the variable will not be changing).

推荐答案

这个,IMHO,是过度使用。
当你说'const int age,...'你实际上说的是你甚至不能改变函数内的本地副本。你所做的是使程序员的代码更少的可读性,迫使他使用另一个本地副本,当他想改变年龄/通过非const引用。

This, IMHO, is overusing. When you say 'const int age,...' what you actually say is "you can't change even the local copy inside your function". What you do is actually make the programmer code less readable by forcing him to use another local copy when he wants to change age/pass it by non-const reference.

任何程序员都应该熟悉传递引用和传递值之间的区别,就像任何程序员应该理解const一样。

Any programmer should be familiar with the difference between pass by reference and pass by value just as any programmer should understand 'const'.

这篇关于C ++ const关键字 - 自由使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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