更改const对象的数组成员的元素
Changing the elements of an array member of a const object
谁能给我解释一下为什么下面的代码工作:
#include <iostream>
class Vec
{
int *_vec;
unsigned int _size;
public:
Vec (unsigned int size) : _vec (new int [size]), _size(size) {};
int & operator[] (const int & i)
{
return _vec[i];
}
int & operator[] (const int & i) const
{
return _vec[i];
}
};
int main ()
{
const Vec v (3);
v[1] = 15;
std::cout << v[1] << std::endl;
}
即使我们改变了const对象的内容,它也能很好地编译和运行。这怎么可以?
是关于类的成员的。您不能更改v._vec
的值,但是更改v._vec
指向的内存的内容是没有问题的。
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- 为什么 2 个相同数组的元素彼此相等
- 将数组的元素添加到链表中
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 从字符数组的元素中减去'a'是什么意思
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 是否可以使用 new 指定具有宏常量的动态分配数组的元素?
- 交换函数不是在 C++ 中交换 2D 数组的元素
- C++将字符串数组的元素存储到变量中
- C++线性搜索算法,确定数组中元素的数量
- 将C++浮点数组成员直接封送到 C#,而无需复制
- 如何输入数组的元素,每次获得新元素时,我们将其放在数组的中间?
- C++向数组添加元素并调整数组大小
- 用于对项目进行分组并将单个项目映射到其他组成员的数据结构
- C++:将类数组的元素替换为 const 成员
- 正在返回指针数组成员变量的元素
- 更改const对象的数组成员的元素