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

Vin*_*ieu 2 c++ oop const

你能解释为什么我不能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);
}
Run Code Online (Sandbox Code Playgroud)

当我调用时f(A),我已经定义了const Array &Ain f但是元素void f()也是可变的,但是当我尝试使用代码行时A.n = 10,它是不可变的.

也许我应该定义一个const重载运算符或其他东西,以便使所有元素都是Arr不可变的.

问题:如何制作Arr不可变元素?

Moh*_*ain 6

也许我应该定义一个'const'重载运算符或其他东西,以使'Arr'中的所有元素都是不可变的.

A.Arr[i]在你的情况下是不可变的.A.Arr是.

您不能执行以下操作:

A.Arr = newaddress;
++A.Arr; // etc
Run Code Online (Sandbox Code Playgroud)

要克服这个问题,摆脱C风格指针(动态内存)并使用:

int Arr[somesize];
Run Code Online (Sandbox Code Playgroud)

或某些容器喜欢std::arraystd::vector确保您的数组是不可变的.

编译失败的实时演示std::vector容器.