问题描述
///////////////////////////////////////
class A {
...
const double funA(void)
{...}
};
A a;
double x = a.funA();
// although the intention is to
// enforce the return value to be const and cannot be
// modified, it has little effect in the real world.
class A2 {
...
double funB(void)
{...}
};
///////////////////////////////////////
class A {
void setA(const double d)
{ // now you cannot change the value of d, so what?
// From my point of view, it is NOT a good practice to change the pass-in parameter
// in this case, unless you want the caller to receive that change
// instead, you can do
// const double dPassIn = d;
/ /then use dPassIn instead.
...
}
};
class A2 {
void setB(double d)
{...}
};
//////////////////////////////////////
根据我的理解,我们应该更喜欢使用 A2 :: funB
和 A2 :: setB
,因为 const 用于 A :: funA
和 A :: setA
都没有意义.
From my understanding, we should prefer tousing A2::funB
and A2::setB
because the const used inboth A::funA
and A::setA
has little meaning.
//更新//
FMOD_RESULT F_API EventSystem::getReverbPresetByIndex(const int index,
FMOD_REVERB_PROPERTIES *props, char **name = 0);
我认为FMOD是一个设计良好的软件包,它确实在函数参数列表内使用了 const int
.现在,我同意 A :: setA(const double d)
有优势.
I consider FMOD is a well-designed package and it does use const int
inside function parameter list.Now, I agree that the A::setA(const double d)
has its edge.
推荐答案
按值返回时,该常数无效,因为无论如何不能强制执行该常数.一些编译器发出警告.但是,将指针/引用返回常量数据确实很有意义.
When returning by value the constant has no effect as it cannot be enforced anyway. Some compilers issue a warning. However it DOES make sense to return a pointer/reference to constant data.
在将参数传递给函数时,最好(更安全,允许编译器优化)将其作为常量传递,除非您绝对需要更改数据.
When passing an argument into a function it is preferable (safer, allows for compiler optimizations) to pass it as a constant unless you absolutely need to change the data.
这篇关于使用"const"的好处在于:标量类型?(例如,"const double"或"const int")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!