【问题标题】:How to avoid operator's or method's code duplication for const and non-const objects? [duplicate]如何避免 const 和 non-const 对象的运算符或方法的代码重复? [复制]
【发布时间】:2011-08-09 18:26:12
【问题描述】:

可能重复:
How do I remove code duplication between similar const and non-const member functions?

我的任务是实现 c++ 矢量模拟。我已经为 2 个案例编写了 operator[]。

T myvector::operator[](size_t index) const {//case 1, for indexing const vector
    return this->a[index];   
} 
T & myvector::operator[](size_t index) {//case 2, for indexing non-const vector and assigning values to its elements
    return this->a[index];
}

如您所见,代码完全相等。对于这个例子(只有一个代码行)来说这不是问题,但是如果我需要为 const 和 non-const 情况实现一些运算符或方法并分别返回 const 或引用值,我该怎么办?每次我在其中进行更改时,只需复制粘贴所有代码即可?

【问题讨论】:

  • 为什么在 const 版本中按值返回。你可以返回一个常量引用。

标签: c++ operators duplication


【解决方案1】:

这里是 const_cast 的少数几个好的用途之一。像往常一样写你的非 const 函数,然后像这样写你的 const 函数:

const T & myvector::operator[](size_t index) const {
    myvector<T> * non_const = const_cast<myvector<T> *>(this);
    return (*non_const)[index];
} 

【讨论】:

  • 这有效地击败了const。这和任何用途一样糟糕。
  • @Potatoswatter:当然它打败了 const。这就是它的目的。
  • 后期编辑:为了复制这个被欺骗的问题的答案,您需要在非常量方法中将 to const 转换为。这种方式是违法的。
  • @Potatoswatter:不,这不违法。
  • @Potatoswatter - 不,这不违法。修改 const 对象是未定义的行为,可以使用非常量指针或引用来读取它。如果非 const operator[] 修改了对象,那么你就有麻烦了,但这里没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多