如何避免 const 和非 const 对象的运算符或方法的代码重复?
我的任务是实现 C++ 向量模拟。我已经为两种情况编写了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 或引用值,我该怎么办?每次更改代码时只需复制粘贴所有代码吗?
Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?
My task is to implement c++ vector analogue. I've coded operator[] for 2 cases.
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];
}
As you can see, the code is completely equal. It's not a problem for this example (only one codeline), but what should I do if I need to implement some operator or method for both const and non-const case and return const or reference value, respectively? Just copy-paste all the code everytime I make changes in it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里 const_cast 的几个好用途之一。像平常一样编写你的非 const 函数,然后像这样编写你的 const 函数:
One of the few good uses of const_cast here. Write your non const function as normal, then write your const function like so: