c++运算符重载报错,如何解决?


#include <iostream>
using namespace std;
struct box
{
  long num;
  int operator+(const box &b1,const box &b2) const
  {
    return b1.num + b2.num;
}
box b_one,b_two;
int main()
{
  b_one.num = 2000;
  b_two.num = 2000;
  cout << b_one + b_two;
  return 0;

操作系统:Windows 10
初步解决方法:删除const,方法没有效果

#include <iostream>
using namespace std;
struct box
{
  long num;
  int operator+(const box &b1) const
  {
    return num + b1.num;
  }
};
struct box b_one,b_two;
int main()
{
  b_one.num = 2000;
  b_two.num = 2000;
  cout << b_one + b_two;
  return 0;
}


int operator+(const box &b1,const box &b2) constc 不对
参考

你题目的解答代码如下:

#include <iostream>
using namespace std;
struct box
{
  long num;
  int operator+(const box &b2) const
  {
    return this->num + b2.num;
  }
};
struct box b_one,b_two;
int main()
{
  b_one.num = 2000;
  b_two.num = 2000;
  cout << b_one + b_two;
  return 0;
}

或者

#include <iostream>
using namespace std;
struct box
{
  long num;
  friend int operator+(const box &b1,const box &b2)
  {
    return b1.num + b2.num;
  }
};
struct box b_one,b_two;
int main()
{
  b_one.num = 2000;
  b_two.num = 2000;
  cout << b_one + b_two;
  return 0;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

如果你贴的代码就是你出错的代码,我想说的是先把最基本的语法搞清楚,至少括号要闭合。

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632