作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我类有一个赋值运算符
template<typename T>
T& array<T>::operator[](int value);
这个方法可以像常量和非常量方法一样使用:
array[100] = value; // None const cause if size > array.size(): resize it!
std::cout << array[0]; // const
如果我的对象被实例化为 const 对象并要求我调整它的大小,我必须抛出异常。
我怎么知道我被实例化为一个 const 对象?
最佳答案
只需添加带有 const
修饰符的第二个版本的 []
运算符,它将为 const 对象调用。
这个用于非 const 对象:
template<typename T>
T& array<T>::operator[](int value);
这个将被调用为 const 对象:
template<typename T>
T& array<T>::operator[](int value) const;
也就是说不要忘记 C++ 中的 const
非常弱,一个简单的 const_cast
将绕过它,因此您也可以考虑另一种保护。
编辑:注意(见注释)根据您的操作,您可以将 const
函数的返回类型声明为 const T&
.这可能是您的情况(如果集合是 const
那么它的元素也必须是 const 吗?)。
关于c++ - 当 this 实例化为 const 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21286871/
出于好奇,我尝试了一些原型(prototype)制作,但似乎只允许在第一个位置使用子例程的原型(prototype) &。 当我写作时 sub test (&$$) { do_somethin
我需要开发一个类似于 Android Play 商店应用程序或类似 this app 的应用程序.我阅读了很多教程,发现几乎每个教程都有与 this one 类似的例子。 . 我已经开始使用我的应用程
考虑一个表示“事件之间的时间”的列: (5, 40, 3, 6, 0, 9, 0, 4, 5, 18, 2, 4, 3, 2) 我想将这些分组到 30 个桶中,但桶会重置。期望的结果: (0, 1,
我是一名优秀的程序员,十分优秀!