C++基础问题:运算符重载(1)

TrueZq 2003-01-17 07:46:26
#include <iostream.h>

class Integer{
int i;
public:
Integer(int ii=0):i(ii) {}
const int GetValue()const {return i;}
void SetValue(int ri) { i=ri; }

Integer operator+(const Integer &rI)
{
return Integer(i+rI.GetValue());
}

};

void main()
{
Integer a(1),b(2),c;
c=a+3; //请解释此句
cout<<c.GetValue()<<endl;
}
c=a+3 为什么可以执行?
...全文
15 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
web_spider 2003-01-17
  • 打赏
  • 举报
回复
更正:
Integer Integer::Operator(int),应该是:
Integer Integer::Operator()(int),
web_spider 2003-01-17
  • 打赏
  • 举报
回复
conversion也是有一个参数的构造函数的一个
隐含特性。遇到c=a+3后编译器首先寻找
Integer::Operator+(int)和Operator+(Integer,int)
类型的函数(操作符),如果没找到,就看看能不能找到一个类型转换函数
(可能是Integer Integer::Operator(int),也可能是类Integer的
只有一个参数的构造函数Integer::Integer(int) ),从而生成一个临时对象,之后进行运算。为避免只有一个参数的构造函数被作为一个类型转换的函数,可以加修饰符explicit,这也是避免很多不必要的bug的一种常用措施。
web_spider 2003-01-17
  • 打赏
  • 举报
回复
起始用Integer(int ii=0)对3执行了一次类型转换,
生成一个临时对象Integer temp=Integer(3);
如果把Integer(int ii=0):i(ii) {}
改为:explicit Integer(int ii=0):i(ii) {}
那么,程序就会报错:
error C2679: binary '+' : no operator defined which takes a right-hand operand of type 'const int' (or there is no acceptable conversion)




gosirius 2003-01-17
  • 打赏
  • 举报
回复
a+3相当于Integer::Operator+(3);
他返回一个Integer类,付给c
严格来说还应该有一个拷贝构造函数来执行=的操作。
bugfree 2003-01-17
  • 打赏
  • 举报
回复
a+3 ===> operator+(a,3)
c= ====> will use the default assignment function

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧