【问题标题】:No operator "[ ]" matches these operands C++没有运算符“[]”与这些操作数匹配 C++
【发布时间】:2022-01-10 01:30:48
【问题描述】:
const DayOfYearSet::DayOfYear DayOfYearSet::operator[](int index){

        if(index < 0){
            
            cout << "Error! Index cannot be negative.." << endl;
            exit(1);
        }

        if(index >= _size){

            cout << "Error! Index overflows the array size.." << endl;
            exit(1);
        }

        return _sets[index];
    }

    const DayOfYearSet DayOfYearSet::operator+(const DayOfYearSet &other){

        vector <DayOfYear> temp;
        for(auto i = 0; i < other.size(); ++i){
            temp.push_back(other[i]);
            .
            .
            .


        }
    }

嘿,我在代码的temp.push_back(other[i]) 行中有一个问题,编译器说没有运算符“[]”与这些操作数匹配。如您所见,我将索引运算符重载为成员函数,但它不起作用?我在这里做错了什么?提前谢谢..

编辑:_sets 是 DayOfYear* _sets 作为类 DayOfYearSet 的私有数据成员。

【问题讨论】:

  • DayYearOfSeat::operator[] 不是const 成员函数。在DayOfYearSet::operator+ 中,other 是一个const DayOfYearSet,所以你不能在它上面调用other[i]。为了比较,看看std::vectorconst 和非const 版本的operator[]

标签: c++ operator-overloading


【解决方案1】:

您正在尝试在const DayOfYearSet &amp;other 上使用operator[],但该函数被定义为仅适用于 const 的对象。

您应该正确地对该函数进行 const 限定。

const DayOfYearSet::DayOfYear DayOfYearSet::operator[](int index) const
//                     This function can be used on const objects ^^^^^

【讨论】:

    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多