【发布时间】:2017-11-29 01:13:29
【问题描述】:
使用一个比另一个有什么优势:
class Foo
{
public:
const int& get() const
{
// stuff here
return myInt;
}
int& get()
{
return const_cast<int&>(static_cast<const Foo*>(this)->get());
}
};
或者
class Foo
{
public:
int& get()
{
// stuff here
return myInt;
}
const int& get() const
{
return const_cast<Foo*>(this)->get();
}
};
我只使用了第一个,但我看到第二个在某个地方使用过,所以我想知道。
评论// stuff here 可能是一项重要的检查,例如检索表的索引以返回表成员的引用(例如:myInt = myTable[myComputedIndex];),因此我不能将其公开。因此 table 和任何成员都不是 const。
【问题讨论】:
-
为什么要在这种情况下使用吸气剂?改为公开
myInt。 -
πάντα ῥεῖ 说的差不多。为了让自己成为一个笨重的可公开访问的成员,您会遇到很多麻烦和样板。
-
static_cast<>也是多余的。 -
@Aconcagua 可以想象很多事情。我说的是问题中的示例。
-
正确执行 getter/setter 函数的方法是不执行它们。