为什么我不能声明对可变对象的引用? (“引用不能被声明为可变的”) [英] Why can't I declare a reference to a mutable object? ("reference cannot be declared mutable")

查看:381
本文介绍了为什么我不能声明对可变对象的引用? (“引用不能被声明为可变的”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有 test.cpp ,如下所示:

Let's say we have a test.cpp as follows:

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成员函数可以更改类成员引用的对象:

There is no reason to have a reference member mutable. Why? Because const member functions can change the object which is referenced by a class member:

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

这篇关于为什么我不能声明对可变对象的引用? (“引用不能被声明为可变的”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆