gpt4 book ai didi

c++ - 当 this 实例化为 const 时抛出异常

转载 作者:行者123 更新时间:2023-11-28 00:34:59 25 4
gpt4 key购买 nike

我类有一个赋值运算符

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com