gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:04:19 25 4
gpt4 key购买 nike

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

为什么该类允许从const public 进行修改

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

这是我的代码:

主要.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;
}

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;
};

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;
}

最佳答案

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

int* tab

标签只包含一个地址。然后在

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

你不修改这个地址,你修改它后面的一些内存。因此,您无需修改​​您的类(class)。

如果相反,你使用了

std::vector<int> tab

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

关于c++ - 为什么我可以在 C++11 中用 const 函数修改类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48824408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com