加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么可以通过const成员函数修改引用成员?

发布时间:2020-12-16 05:39:01 所属栏目:百科 来源:网络整理
导读:即使一个const成员函数将修改一个成员的值,下面将使用 compile.怎么会这样 ? #include iostreamstruct foo{ std::string str; foo(std::string other) : str(other) {} void operator()(std::string some) const { str += some; }};int main(){ std::string
即使一个const成员函数将修改一个成员的值,下面将使用 compile.怎么会这样 ?
#include <iostream>

struct foo
{
    std::string &str;
    foo(std::string &other) : str(other) {}

    void operator()(std::string &some) const
    {
        str += some;
    }
};

int main()
{
    std::string ext("Hello");
    foo a{ ext };

    std::string more(" world!");
    a(more);

    cout << a.str;
    return 0;
}

解决方法

类成员函数的const限定符表示该成员函数(例如,foo :: operator()const)不能从客户端的角度更改对象的状态(即,它是抽象状态).这不是说对象的原始位不会改变.

它是for C编译器将对象视为原始位,除非它们可以解析the problem of aliasing.在您的情况下,编译器不能.这是由于存在非常数别名(即std :: string& str)的事实,因此对象的状态是可修改的.

也就是说,在对象a上调用operator()不改变a的状态(即,尽管ext已经改变,但str仍然是ext的别名).

上面也解释了为什么用指向常量的指针(即,std :: string * const str)指向一个对象不能保证对象不被修改.它只保证对象不会通过该指针进行更改.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读