///////////////////////////////////////
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)
{...}
};
//////////////////////////////////////
Run Code Online (Sandbox Code Playgroud)
从我的理解,我们应该更喜欢使用A2::funB和A2::setB因为两者中使用的constA::funA并A::setA没有什么意义.
//更新//
FMOD_RESULT F_API EventSystem::getReverbPresetByIndex(const int index,
FMOD_REVERB_PROPERTIES *props, char **name = 0);
Run Code Online (Sandbox Code Playgroud)
我认为FMOD是一个设计良好的包,它确实使用const int内部函数参数列表.现在,我同意A::setA(const double d)它的优势.
按值返回时,常量无效,因为无论如何都无法强制执行.一些编译器发出警告.但是,将指针/引用返回到常量数据是有意义的.
将参数传递给函数时,最好(更安全,允许编译器优化)将其作为常量传递,除非您绝对需要更改数据.