c++ - 如何在 OOP C++ 中使用 Const 类型类?

标签 c++ oop constants

你能解释一下为什么我不能在类中使用 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 &Avoid 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 demostd::vector 作为容器的编译失败。

关于c++ - 如何在 OOP C++ 中使用 Const 类型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215970/

相关文章:

c++ - 使用迭代器递增

c++ - VS2012 LibRTMP包含c到c++

java - 面向对象的执行

perl - Moose OOP 还是标准 Perl?

php - 查找或列出 PHP 文件中使用的所有常量

c++ - 函数的 Const 声明

c++ - 使 Qt 应用程序在最后一个窗口关闭时不退出

c++ - 矩阵 37x37 的行列式

php - 使用名称中带有变量的命名空间

c++ - 何时在函数 args 中使用 const 和 const 引用?