gpt4 book ai didi

c++ - 指向const对象的指针可以改变对象吗?

转载 作者:行者123 更新时间:2023-12-04 07:39:56 25 4
gpt4 key购买 nike

指向 const 对象的指针不允许更改对象。例如:

class foo {
public:
int m_data;

foo() : m_data{11} {}
};

void change(const foo *obj)
{
obj -> m_data = 21; // gives error, normal
}
这是正常且正常的行为。
我不明白的是,当我们添加一个额外的指针变量时,无论是相同类型(如 foo * )还是其他类型(如 bar * ),但不是基本类型,如 int * ,然后我们可以更改指针指向的值(从指向 const 类型本身的指针)。
这怎么可能?
class foo {
public:
int m_data;
foo *m_next;

foo() : m_data{11}, m_next{nullptr} {}
};

void change(const foo *obj)
{
obj -> m_next -> m_data = 21; // does not give any error! why?
}
如果我们在 foo 中使用其他类型,也会发生这种情况。 , 喜欢 bar * .
为什么会这样?我如何定义函数才能确保我的函数不能更改对象指向的值?

最佳答案

obj -> m_next -> m_data = 21;   // does not give any error! why?
因为这并没有改变对象。此对象的 m_next指针与之前完全相同。
这只会改变任何 m_next是指。无论如何,这与拥有此对象的对象无关 m_next指针。
现在,另一方面,如果您尝试将某些内容分配给 m_next指针本身,而不是它指向的任何东西,那么你会得到你期望的错误。
对象包含的唯一内容是它的枚举成员。这行代码没有改变它们。

关于c++ - 指向const对象的指针可以改变对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67541880/

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