gpt4 book ai didi

c++ - 使成员变量对象可修改但不可赋值

转载 作者:行者123 更新时间:2023-11-30 02:28:58 24 4
gpt4 key购买 nike

我已经四处寻找答案,也许我只是没有使用正确的术语来获得任何结果?

有没有什么方法可以让一个成员变量是 const 的,因为它不能被重新赋值,并且永远是同一个对象,但仍然允许对象本身被修改?很像指向非常量对象的 const 指针的行为,但不是实际指针?

我看到的主要用例是合成。假设 Foo 有一个 Bar,您希望能够访问和修改该 Bar,但不更改 Foo 拥有的 Bar。只需更改该 Bar 上的属性/调用非常量方法。有什么办法吗?

最佳答案

不适用于 const 正确性机制;它太原始了(它只是一个位:“改变”或“不改变”)。

但是,您可以将分配标记为私有(private),将容器标记为友元,这样只允许分配容器方法,但可以将修改器标记为公共(public)以供其他人使用。

class Foo {
public:
int x, y;
Foo() : x(0), y(0) {}
friend class Bar;
private:
Foo& operator=(const Foo& other){
...
return *this;
}
};

class Bar {
public:
Foo foo;
Bar(){
foo = Foo(); // OK from here
};
};

void baz() {
Bar bar;
bar.foo.x = 42; // Ok assigning a member of foo
bar.foo = Foo(); // Invalid from here (doesn't compile)
}

关于c++ - 使成员变量对象可修改但不可赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40164970/

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