关于隐式类型转换

league1991 2009-03-30 11:25:04
我定义了两个基类:Integer和Real,再派生出IntReal,现在想在IntReal重载加号,再定义类型转换构造函数,把基类转换成派生类,为什么重载的时候就不能识别呢?

程序如下:#include<iostream.h>
class Integer
{
public:
Integer(int a):i(a){}
Integer(const Integer&a){i=a.i;}
int i;
};
class Real
{
public:
Real(double a):f(float(a)){}
Real(const Real&a){f=a.f;}
float f;
};
class IntReal:public Integer,public Real
{
public:
IntReal(const Integer a):Integer(a),Real(0){}
IntReal(const Real a):Real(a),Integer(0){}
IntReal(int a=0):Integer(a),Real(0){}
IntReal(double a):Integer(0),Real(a){}
friend IntReal operator+(IntReal&a,IntReal&b);
};
IntReal operator+(IntReal&a,IntReal&b)
{
IntReal c(0);
if(a.f==0&&b.f==0)
c.i=a.i-b.i;
else
c.f=(float)a.i+a.f+(float)b.i+b.f;
return c;
}
void main()
{
Integer a(1),b(2),r1(0);
Real c(3),d(4),r2(0);
c+d;
}

编译时候报告不能进行类型转换:no operator defined which takes a left-hand operand of type 'class Real' (or there is no acceptable conversion)
请问这是为什么呢?我用vc6。
...全文
168 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengzhixi 2009-03-31
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 league1991 的回复:]
想测试重载的加法运算,结果编译错误。。。
[/Quote]

你的Real类根本就没重载“+”运算符号啊。你想用IntReal重载的“+”怎么可能呢。
league1991 2009-03-31
  • 打赏
  • 举报
回复
想测试重载的加法运算,结果编译错误。。。
league1991 2009-03-31
  • 打赏
  • 举报
回复
可是它为什么不会把Real类转换成IntReal类进行运算呢?IntReal类里有相应的构造函数哦。另外一个IntReal类和Integer类相加也会出现错误,为什么呢?
Sco_field 2009-03-30
  • 打赏
  • 举报
回复
void main()
{
Integer a(1),b(2),r1(0);
Real c(3),d(4),r2(0);
c+d; // 你这个是什么意思?
}

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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