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的用法将被报错

 

 

原文地址:https://www.cnblogs.com/suui90/p/13129916.html