如何避免const和非const对象的运算符或方法的代码重复? [英] How to avoid operator's or method's code duplication for const and non-const objects?

查看:119
本文介绍了如何避免const和非const对象的运算符或方法的代码重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何删除相似的const和非const成员函数之间的代码重复?

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

我的任务是实现c ++矢量模拟.我已经将operator []编码为2种情况.

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];
}

如您所见,代码是完全相等的.对于此示例(仅一个代码行)来说,这不是问题,但是如果我需要为const和非const情况都实现一些运算符或方法并分别返回const或引用值,该怎么办?每次更改时都复制粘贴所有代码吗?

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?

推荐答案

此处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:

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

这篇关于如何避免const和非const对象的运算符或方法的代码重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆