为什么我可以在C++ 11中使用const函数修改类?

Aut*_*ern 7 c++ c++11

我是CPP的新手,我不知道为什么setValue() const同时它是一个const.

为什么该类允许修改 const public

看起来很奇怪,g ++ -Wall或MS Visual C++没有错误

这是我的代码:

main.cpp中

#include <iostream>
#include <cassert>
#include "DArray.h"

int main(void)
{
    DArray darray(1);
    darray.setValue(0, 42);
    assert(darray.getValue(0) == 42);
    darray.~DArray();
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

DArray.h

class DArray
{
private:
    int* tab;

public:
    DArray();
    DArray(unsigned int n);
    ~DArray();

    int& getValue(unsigned int n) const;
    void setValue(unsigned int n, int value) const;
};
Run Code Online (Sandbox Code Playgroud)

DArray.cpp

#include "DArray.h"

DArray::DArray()
{

}

DArray::DArray(unsigned int n)
{
    tab = new int[n];
}

DArray::~DArray()
{
    delete[] tab;
    tab = nullptr;
}

int& DArray::getValue(unsigned n) const
{
    return tab[n];
}

void DArray::setValue(unsigned n, int value) const // HERE
{
    tab[n] = value;
}
Run Code Online (Sandbox Code Playgroud)

小智 17

这是因为你没有修改它.当你这样做时:

int* tab
Run Code Online (Sandbox Code Playgroud)

选项卡仅包含一个地址.然后进去

void DArray::setValue(unsigned n, int value) const // HERE
{
    tab[n] = value;
}
Run Code Online (Sandbox Code Playgroud)

你没有修改这个地址,你修改了一些内存.因此,您不会修改您的课程.

相反,如果你使用了

std::vector<int> tab
Run Code Online (Sandbox Code Playgroud)

你会在setValue中出错,因为你会修改你的类的元素.


Fra*_*101 6

首先,不要明确地调用类的析构函数,当变量自动超出范围时,将调用它.

darray〜DArray();

const在该方法中承诺的是不会修改成员变量.该变量int* tab是指向int的指针.使用setValue函数,您不会更改指针的地址(承诺不会被方法签名中的最终const更改),而是指向它指向的int值.这可以.

但是,如果更改指针地址(例如,使用)tab = nullptr,您将看到编译器错误,如:

错误:在只读对象中分配成员'DArray :: tab'