class A
{
public:
A(int arg1, int arg2);
~A();
A &operator = ( A &other);
A operator + ( A &other);
private:
int a, b; }; A::A(int arg1, int arg2)
{
a = arg1;
b = arg2;
} A::~A()
{ }
A &A::operator=( A &other)
{
if (this == &other)
{
return *this;
} this->a = other.a;
this->b = other.b;
return *this;
} A A::operator+( A &other)
{
return A(a+other.a, b+other.b);
// return other;
}

上面的这个类中重载了=和+号运算符, 但是参数都是引用,而不是const的引用,这样在遇到形如

A a(1, 2);

a + A(3, 4);

的运算时就会出现错误,原因如下:

a + A(3, 4)等价于a.operator +(A(3, 4))

这里要提到的是函数的返回值不能作为左值(可以参见http://blog.csdn.net/sunshinewave/article/details/7830701

但是类中的函数声明确是

A operator + ( A &other)

说明other在函数中是可以修改的,这就产生了矛盾,所以编译器会提示无法把A类型的变量转换成A&的错误提示

总结:在类中重载运算符时要把形参表示为const A&的形式,不仅为了减少开销

 

最新文章

  1. Linux安全基础:配置network
  2. C# 获取汉字拼音首字母
  3. Java利用aspose-words将word文档转换成pdf(破解 无水印)
  4. jquery对于table的操作
  5. 点的双联通+二分图的判定(poj2942)
  6. Unity3d 一些 常见路径
  7. POJ2251Dungeon Master
  8. 如何获取、下载、安装fortran编译工具ifort
  9. qt安装遇到的错误
  10. SWT中在treeview中显示图片
  11. Influxdb1.2.2安装_Windows
  12. no suitable driver found for jdbc:mysql//localhost:3306/..
  13. bzoj:3730: 震波
  14. Percona监控MySQL模板详解
  15. Flutter 实现原理及在马蜂窝的跨平台开发实践
  16. log4cplus 简单记录
  17. Spring Cloud Stream同一通道根据消息内容分发不同的消费逻辑
  18. February 18th, 2018 Week 8th Sunday
  19. Struts2——namespace、action、以及path问题
  20. QQ空间说说如何批量删除

热门文章

  1. webpack打包不引入vue、echarts等公共库
  2. 防止SQL/XSS攻击
  3. sgu209:Areas(计算几何)
  4. 统计推断(statistical inference)
  5. iis启动 服务无法在此时接受控制信息。 (异常来自 HRESULT:0x80070425)
  6. Delphi png、bmp、gif等图片格式转换成jpg
  7. C++第11周(春)项目4 - 类族的设计
  8. phpstorm 删除空行
  9. ANDROID 中设计模式的採用--结构型模式
  10. 使用bcc32做在windowXP上qt3.2.1编译环境的配置