索引运算符过载

Overloading indexing operator

本文关键字:运算符 索引      更新时间:2023-10-16

我正在尝试重载索引运算符[]。我有两个版本我需要同时使用它们,但当我构建项目时,会调用其中一个,并且无论在哪里使用第二个:Invalid operands to binary expression double and Quarters,都会出现错误。

这是第一个:

Quarters& Security :: operator [] (QuarterType quarter){
    return quartersData[static_cast<int>(quarter)];
}

第二个:

const double& Security :: operator [] (QuarterType quarter) const{
    return (quartersData[static_cast<int>(quarter)].getPrediction());
}

问题出在哪里?我能做些什么来解决它?

重写不考虑返回类型。由于在这两种情况下,参数类型都是相同的,因此重写只考虑对象的const性。如果您的对象不是const,那么无论您下一步要对它做什么,都将调用operator[]的非常量版本。