gcc test.cpp t-6ren">
gpt4 book ai didi

c++ - 为什么我不能声明对可变对象的引用? ("reference cannot be declared mutable")

转载 作者:IT老高 更新时间:2023-10-28 12:52:32 24 4
gpt4 key购买 nike

假设我们有一个 test.cpp 如下:

class A;

class B
{
private:
A mutable& _a;
};

编译:

$> gcc test.cpp
test.cpp:6:20: error: reference ‘_a’ cannot be declared ‘mutable’ [-fpermissive]

我的 gcc:

$> gcc --version
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

为什么?

最佳答案

没有理由让引用成员可变。为什么?因为 const 成员函数可以改变类成员引用的对象:

class B {
public:
B(int var) : n(var) {};
void Set(int val) const { n = val; } //no error
void SetMember(int val) const { m = val; } //error assignment of member `B::m' in read-only structure
protected:
int& n;
int m;
};

关于c++ - 为什么我不能声明对可变对象的引用? ("reference cannot be declared mutable"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8469209/

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