代码什么的要哭了 2022-04-30 17:36 采纳率: 67.9%
浏览 80
已结题

复数类运算符重载,复数加整数计算问题

不知道为什么main函数中的2+z4一直报错,但是main函数是给定的不能改,有人知道怎么改吗,感谢

//友元函数计算2+z
#include<iostream>
using namespace std;

class Cmycomplex
{
public:
    Cmycomplex(double a=0,double b=0);//缺省构造函数 
    void Set(double, double);
    Show();
    Cmycomplex operator+(int&);
    Cmycomplex operator+(Cmycomplex &);//声明运算符+ 重载函数 
    friend Cmycomplex operator+(int &, Cmycomplex &); 
private:
    double real;//复数实部 
    double imag;//复数虚部 
};

Cmycomplex::Cmycomplex(double a, double b)
{
    real = a;
    imag = b;
}

void Cmycomplex::Set(double a, double b)
{
    real = a;
    imag = b;
}

Cmycomplex Cmycomplex :: operator+(Cmycomplex &c2)
{
   return Cmycomplex(real+c2.real,imag+c2.imag);
}

Cmycomplex Cmycomplex::operator+(int&i)
{
  return Cmycomplex(real+i,imag);
}


Cmycomplex operator+(int &m, Cmycomplex &n)
{
    return Cmycomplex(m+n.real,n.imag);
}
Cmycomplex::Show()
{
    if (imag >= 0) cout << '(' <<  real << '+'  << imag << 'i' << ')';
    if (imag < 0) cout << '(' <<  real << "-" << imag << 'i' << ')';
}
//StudybarCommentBegin
int main()
{
    Cmycomplex z1(3,4),z2(7),z3,z4(z1);
    double x,y;
    cin>>x>>y;
    z3.Set(x,y);
    cout<<endl;
    z3=z3+z2;
    z3.Show();
    //int i=2;
    z4=2+z4;
    cout<<endl;
    z4.Show();
    z4=z4+2;
    cout<<endl;
    z4.Show();

} 
//StudybarCommentEnd 

  • 写回答

1条回答 默认 最新

  • SmallAntJ 2022-04-30 23:51
    关注

    有两种改法:

    1. 参数用常量引用:

      Cmycomplex operator+(const int &);
      friend Cmycomplex operator+(const int &, Cmycomplex &); 
      
    2. 参数不使用引用:

      Cmycomplex operator+(int);
      friend Cmycomplex operator+(int, Cmycomplex &); 
      

    另外Show函数前面需要加个void

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月9日
  • 已采纳回答 5月1日
  • 创建了问题 4月30日

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染