如何在 OOP C++ 中使用 Const Type Class?

How to use Const Type Class in OOP C++?

你能解释一下为什么我不能在 class 中使用 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::arraystd::vector,以确保您的数组是不可变的。

Live demo 编译失败,std::vector 作为容器。

const Array &A表示A对象被当作常量,所以它的成员不能被修改;但其他对象,例如 A.Arr 指向的数组中的对象,则不是。

n = 10;不可能不是因为Aconst,而是因为友元函数不是成员,所以没有nconst 会阻止 A.n = 10;

您可以通过仅允许通过成员函数而不是通过指针访问来防止修改数组:

public:
    Type       & operator[](size_t i)       {return Arr[i];}
    Type const & operator[](size_t i) const {return Arr[i];}

现在 A[i] 只有在 A 是可变的情况下才能用于修改。

只是为了完成答案,因为你的 class 被命名为 Array,你应该相应地重载数组下标运算符:

int &operator[](int index) { return Arr[index]; } // non-const overload

int operator[](int index) const { return Arr[index]; } // const overload

有了它,您将不再需要弄乱那个朋友功能。