类继承时 operator+ 的问题

BillLeecn 2010-06-24 08:14:21
有一个基类和一个子类。我想要使两个 Sub 对象相加是返回一个 Sub 对象
class Base{
friend Base operator+(Base&, Base&);
};
class Sub: public{
friend Sub operator+(Sub& a, Sub& b){
return a + b;
}
};

这样的代码将会导致编译错误
error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
请问怎样改代码才能实现这样的用法(基类 Base 不能改)
...全文
99 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wyz007134 2010-06-25
  • 打赏
  • 举报
回复
你们没发现编译器的报错很搞笑么?
error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
它好像很无奈...
tananade 2010-06-24
  • 打赏
  • 举报
回复
呵呵,你根本没有定义成功,正如上面所说的,这会递归
属于递归定义
selooloo 2010-06-24
  • 打赏
  • 举报
回复
Base对象和Sub对象相加时会产生二义性
cattycat 2010-06-24
  • 打赏
  • 举报
回复
你并没有实现operator+啊。
可以
Sub temp;
temp.x=a.x+b.x;
return temp;
类似这样的。
jizhongqing 2010-06-24
  • 打赏
  • 举报
回复
class Base
{
public:
Base(int x = 0, int y = 0) : m_x(x), m_y(y) {}

friend Base operator+(const Base& a, const Base& b);

// 这里不写 get,set了,
// int GetX()
// {
// return m_x;
// }
// int GetY()
// {
// return m_y;
// }

//private:
int m_x;
int m_y;
};

Base operator+(const Base& a, const Base& b)
{
Base c;
c.m_x = a.m_x + b.m_x;
c.m_y = a.m_y + b.m_y;

return c;
}

class Sub: public Base
{
public:
Sub(int x = 0, int y = 0, int z = 0) : Base(x, y), m_z(z) {}
friend Sub operator+(const Sub& a, const Sub& b);

//private:
int m_z;
};

Sub operator+(const Sub& a, const Sub& b)
{
// 直接使用父类的成员不太好,实际中父类应该提供访问函数。。。
Sub c;
c.m_x = a.m_x + b.m_x;
c.m_y = a.m_y + b.m_y;
c.m_z = a.m_z + b.m_z;

return c;
}


int _tmain(int argc, _TCHAR* argv[])
{
Base a(1, 2), b(3, 4), c;
c = a + b;

Sub d(1,2), e(3, 4, 5), f;
f = d + e;

return 0;
}
we_sky2008 2010-06-24
  • 打赏
  • 举报
回复

friend Sub operator+(Sub& a, Sub& b)
{
return a + b;
}


这个会导致无穷递归的
fallening 2010-06-24
  • 打赏
  • 举报
回复
尽量少放在类里边
class Base;
class Derive;

const Base
operator + ( const Base&, const Base& );

const Derive
operator + ( const Derive&, const Derive& );
MK 2010-06-24
  • 打赏
  • 举报
回复
楼主的思路是什么?
什么都没有,继承的时候少了基类名啊
liutengfeigo 2010-06-24
  • 打赏
  • 举报
回复
return a + b;
你因该去调用构造函数啊比如 return Sub(a.xxx+b.xxx);

64,662

社区成员

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

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