具有基本类型的C ++ const修饰符 [英] C++ const modifier with primitive types

查看:116
本文介绍了具有基本类型的C ++ const修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该注意用于基本类型的 const 修饰符吗?

Should I pay attention on const modifier working with primitive types? Which one is more syntactically correct and why?

第一个版本:

float Foo::bar(float a, float b)
{
    return (a + b) / 2.0f;
}

第二版本:

const float Foo::bar(const float a, const float b)
{
    return (a + b) / 2.0f;
}

第三版:

float Foo::bar(const float a, const float b)
{
    return (a + b) / 2.0f;
}

我知道在传递给某些方法时会复制原始类型的变量,但是

I know the primitive-typed variables are copied when passing to some method, but what way is more clear?

推荐答案

我会说第三个版本最正确。

I would say that the third version is most "correct".

您告诉编译器参数为 const ,这是正确的,因为您无需修改​​它们。这样可以帮助编译器进行参数传递和计算的优化。

You tell the compiler that the arguments are const, which is correct since you don't modify them. This can help the compiler with optimizations for passing the arguments, as well as in the calculations.

返回类型不是 const ,因为调用者可能要修改返回的值。如果调用者不想修改返回的值,则由调用者将其分配给 const 变量。

And the return type is not const since the caller may want to modify the returned value. If the caller doesn't want to modify the returned value, then it's up to the caller to assign it to a const variable.

我还会在函数声明中添加 const ,因为函数不会修改对象中的任何内容:

I would also have added const to the function declaration, since the function does not modify anything in the object:

float Foo::bar(const float a, const float b) const

这篇关于具有基本类型的C ++ const修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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