c++类运算符重载遇到的函数形参问题
2024-08-31 22:49:27
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&的形式,不仅为了减少开销
最新文章
- Linux安全基础:配置network
- C# 获取汉字拼音首字母
- Java利用aspose-words将word文档转换成pdf(破解 无水印)
- jquery对于table的操作
- 点的双联通+二分图的判定(poj2942)
- Unity3d 一些 常见路径
- POJ2251Dungeon Master
- 如何获取、下载、安装fortran编译工具ifort
- qt安装遇到的错误
- SWT中在treeview中显示图片
- Influxdb1.2.2安装_Windows
- no suitable driver found for jdbc:mysql//localhost:3306/..
- bzoj:3730: 震波
- Percona监控MySQL模板详解
- Flutter 实现原理及在马蜂窝的跨平台开发实践
- log4cplus 简单记录
- Spring Cloud Stream同一通道根据消息内容分发不同的消费逻辑
- February 18th, 2018 Week 8th Sunday
- Struts2——namespace、action、以及path问题
- QQ空间说说如何批量删除
热门文章
- webpack打包不引入vue、echarts等公共库
- 防止SQL/XSS攻击
- sgu209:Areas(计算几何)
- 统计推断(statistical inference)
- iis启动 服务无法在此时接受控制信息。 (异常来自 HRESULT:0x80070425)
- Delphi png、bmp、gif等图片格式转换成jpg
- C++第11周(春)项目4 - 类族的设计
- phpstorm 删除空行
- ANDROID 中设计模式的採用--结构型模式
- 使用bcc32做在windowXP上qt3.2.1编译环境的配置