常量和重载运算符
const and overloading operator
我有通用的地图对象。我想重载运算符 [],以便map[key]
返回键的值。我制作了两个版本的下标运算符。
非常量:
ValueType& operator[](KeyType key){
常量:
const ValueType& operator[]( KeyType& key) const{
非常量版本工作正常,但是当我创建常量地图时,我遇到了问题。我主要写:
const IntMap map5(17);
map5[8];
我收到这些错误:
ambiguous overload for 'operator[]' (operand types are 'const IntMap {aka const mtm::MtmMap<int, int>}' and 'int')
invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
关于歧义的错误消息反映了您的编译器将您的两个operator[]()
都视为匹配map5[8]
的可能候选项。 两位候选人都同样好(或坏,取决于你如何看待它)。
非const
版本无效,因为map5
const
。
const
版本要求使用右值(文字8
)初始化对KeyType
的非const
引用,这是无效的。 从错误消息中,您的KeyType
int
。
从const
版本的KeyType
参数中删除&
,或将该参数设为const
。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板