为什么我不能声明对可变对象的引用? (“引用不能声明为可变的”)

2024-04-29

假设我们有一个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]

My 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.

Why?


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

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;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我不能声明对可变对象的引用? (“引用不能声明为可变的”) 的相关文章

随机推荐