V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xmyjd
V2EX  ›  C++

C++里, operator=的返回值为什么不是 const& ?

  •  
  •   xmyjd · 2019-10-17 09:21:28 +08:00 · 3571 次点击
    这是一个创建于 1624 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这样不能通过编译。 const T& operator(const T& t);

    必须这样才行 T& operator(const T& t);

    难道会有这样的操作吗: T a,b,c; (a=b)=c;

    7 条回复    2019-10-17 15:51:39 +08:00
    mooyo
        1
    mooyo  
       2019-10-17 09:52:23 +08:00
    T d = (a = b);
    d = c;
    across
        2
    across  
       2019-10-17 09:54:48 +08:00   ❤️ 1
    大声告诉我, = 的意义是什么,const 的意义又是什么?
    wutiantong
        3
    wutiantong  
       2019-10-17 10:45:17 +08:00
    会有。
    运算符重载的函数声明都是有规范的,不要自己想当然。
    koebehshian
        4
    koebehshian  
       2019-10-17 12:41:41 +08:00
    赋值运算符,左边的操作数,必须是的左值 https://en.cppreference.com/w/cpp/language/rule_of_three
    zjsxwc
        5
    zjsxwc  
       2019-10-17 14:50:55 +08:00
    既想赋值修改,又想 const 不得修改,你到底是想修改还是不想修改?
    shfanzie
        6
    shfanzie  
       2019-10-17 15:24:06 +08:00
    2 楼 已结贴
    ipwx
        7
    ipwx  
       2019-10-17 15:51:39 +08:00 via Android
    T& t = (a = b); t = c;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1144 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:33 · PVG 02:33 · LAX 11:33 · JFK 14:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.