你能解释一下为什么我不能在类中使用 const
类型吗?
示例代码:
class Array {
int *Arr;
int n;
public:
Array(int _n = 0) {
Arr = new int[_n];
n = _n;
}
~Array(void) {
delete []Arr;
}
friend void f(const Array &A) {
A.Arr[0] = 3; // why can the Arr[0], Arr[1] be changed the value ?
A.Arr[1] = 4;
// A.n = 10; // can not be changed because of 'const class type'
}
};
void main()
{
Array A(5);
f(A);
}
当我调用 f(A)
时,我在 f
中定义了 const Array &A
但 void f 中的元素()
也是可变的,但是当我尝试使用代码行 A.n = 10
时,它是不可变的。
也许我应该定义一个 const
重载运算符或其他东西,以使 Arr
中的所有元素不可变。
问题如何使 Arr
的元素不可变?
最佳答案
Maybe i should define a 'const' overloading operator or something in order to make all of the elements in 'Arr' are immutable.
A.Arr[i]
在你的情况下不是不可变的。 A.Arr
是。
您不能执行以下操作:
A.Arr = newaddress;
++A.Arr; // etc
要克服这个问题,摆脱 C 风格的指针(动态内存)并使用:
int Arr[somesize];
或者像 std::array
或 std::vector
这样的容器来确保你的数组是不可变的。
Live demo以 std::vector
作为容器的编译失败。
关于c++ - 如何在 OOP C++ 中使用 Const 类型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215970/