【发布时间】:2012-01-14 11:13:08
【问题描述】:
///////////////////////////////////////
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 都没什么意义。
// 更新 //
FMOD_RESULT F_API EventSystem::getReverbPresetByIndex(const int index,
FMOD_REVERB_PROPERTIES *props, char **name = 0);
我认为 FMOD 是一个精心设计的包,它确实在函数参数列表中使用了const int。
现在,我同意A::setA(const double d) 有它的优势。
【问题讨论】:
-
您说最好保持参数不变“...除非您希望调用者接收该更改...”。在这种特殊情况下,调用者不会收到更改,因为参数是按值传递的。您需要传递一个引用/指针。
标签: c++