【发布时间】:2010-09-12 12:46:14
【问题描述】:
假设我有以下class X,我想在其中返回对内部成员的访问权限:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const Z& Z(size_t index) const
{
// identical to non-const X::Z(), except printed in
// a lighter shade of gray since
// we're running low on toner by this point
}
};
两个成员函数X::Z() 和X::Z() const 在大括号内有相同的代码。这是重复代码可能会导致逻辑复杂的长函数出现维护问题。
有没有办法避免这种代码重复?
【问题讨论】:
-
在此示例中,我将在 const 情况下返回一个值,因此您无法进行以下重构。 int Z() const { 返回 z; }
-
对于基本类型,您是绝对正确的!我的第一个例子不是很好。假设我们改为返回一些类实例。 (我更新了问题以反映这一点。)
标签: c++ class constants code-duplication c++-faq