zoukankan      html  css  js  c++  java
  • C++ 返回const对象

    ——不注意时,重载operator+()会造成一个奇异的属性:

     net = force1 + force2; // 1: three Vector objects 

    然而,还可以这样用:

     force1 + force2 = net; // 2: dyslectic programming 

     cout<<(force1 + force2 = net).magval()<<endl; // 3: demented programming 

    这是不合理的(覆盖了创建好的临时对象)但可行的:

    • (2)创建了一个对象和的临时对象,再用net覆盖,之后将其丢弃;
    • (3)在(2)的基础上调用了临时对象的magval()方法,之后才丢弃临时对象

    并且可能发生如下错误:

    if (force1 + force2 == net) 误用为 if (force1 + force2 = net) 

    这同样可能通过编译

    解决由此引发的误用和滥用的办法:

    将返回类型声明为const,这样便不能对临时对象进行修改,因此force1 + force2 = net的用法将被报错

     

     

  • 相关阅读:
    1489 蜥蜴和地下室
    1521 一维战舰
    1596 搬货物
    1873 初中的算术
    CF-799B
    101 pick me up~
    落叶归根
    P1149 火柴棒等式
    P1540 机器翻译
    图论学习十之Sparse table
  • 原文地址:https://www.cnblogs.com/suui90/p/13129916.html
Copyright © 2011-2022 走看看