首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++:重载下标操作符

C++:重载下标操作符
EN

Stack Overflow用户
提问于 2013-06-02 06:56:46
回答 1查看 409关注 0票数 1

我正在实现一个向量,所以我希望它的行为像一个数组。这就是为什么我试图实现下标操作符,但我没有实现正确的行为。

其实现如下所示:

代码语言:javascript
运行
复制
template <typename value_type>
class Vector{ 
    private:
    value_type ** vector ; 
    long size ; 
    long usedSize ; 

    public: 
    /.../ 
    value_type & operator [] (long) ; // For writing.
    const value_type & operator [] (long) const ; // For reading.
    /.../
}

template<typename value_type> 
value_type & Vector<value_type>::operator[] ( long index ) {
    if ( index < 0 || index > usedSize ) 
        return out_of_range () ; 
    else {
        vector[index] = new value_type () ; 
        usedSize++ ; 
        return *(vector[index]) ;
    }
} 

template<typename value_type> 
const value_type & Vector<value_type>::operator[] ( long index ) const {
    if ( index < 0 || index > usedSize ) 
        return out_of_range () ; 
    else { return (*vector[index]) ; }
}

然后我用下面的代码测试对象的行为:

代码语言:javascript
运行
复制
int main (void) { 
    Vector<int> * v = new Vector ( 10 ) ; // Creates a vector of 10 elements.
    (*v)[0] = 3 ; 
    int a = (*v)[0] ; 
    cout << "a = " << a << endl ;
}

我从行刑中得到了这样的结论:

代码语言:javascript
运行
复制
$> a = 0 

一些线程建议使用处理程序类重载赋值操作符,我想知道是否有任何方法可以避免使用处理程序对象来完成任务。

提前谢谢。

从阿根廷来的贡萨洛。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-02 07:52:21

你的假设是错误的

cout << "a =“<< (*v) << endl;

这个

向量常量value_type &

::operatorlong index常量

将会被使用。

事实上,这两次

矢量value_type::operator[](&V)

这样您就可以用新的值“替换”以前的值(同时也会泄漏内存)。

下面应该会有帮助

代码语言:javascript
运行
复制
value_type & Vector<value_type>::operator[] ( long index ) {
    if ( index < 0 || index > usedSize )
        ///out of bounds handling
    else {
        if(vector[index]== 0)
        {
            vector[index] = new value_type () ;
            usedSize++ ;
        }
        return *(vector[index]) ;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16878082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档