c++ - 如何避免 const 和非常量对象的运算符或方法代码重复?

标签 c++ operators duplication

<分区>

Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?

我的任务是实现 C++ vector 模拟。我为 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 和非 const case 实现一些运算符或方法并分别返回 const 或引用值,我该怎么办?每次更改代码时只需复制粘贴所有代码?

最佳答案

这里是 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];
} 

关于c++ - 如何避免 const 和非常量对象的运算符或方法代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5735287/

相关文章:

powershell - 测试字符串的最佳方法是什么?

java - 查找重复的表达式/参数

rust - 核心中的运算符真的是循环定义的吗?

c++ - 在 UDP sendto 中将数据作为结构发送

C++ GCC 为什么这段 sfinae 代码可以用 GCC 4.7 编译,但不能用 4.8 编译?

c++ - 将静态库与 gnu g++ : No such file or directory, Makefile 链接

c# - 如何在 C# 中使用 & 运算符?代码的翻译是否正确?

c# - 在 Visual Studio 2008 (C#) 中复制一个表单

php - SHA 是否足以检查文件重复? (PHP 中的 sha1_file)

c++ - 使用递归函数C++进行乘法