xtggstc 2022-04-08 19:45 采纳率: 100%
浏览 65
已结题

重载成员函数只能有一个参数吗?

重载成员函数只能有一个参数吗?我写的operator-中写一个参数是对的,写了两个参数就是说参数太多了

img

#include <iostream>
using namespace std;
class complex {
public:
    double real, imag;
    complex(double r=0.0,double i=0.0):real(r),imag(i){}
    complex operator-(complex& a,complex &e);
    
};
complex operator+(complex& b, complex& c) {
    return complex(b.real + c.real, b.imag + c.imag);
}
complex complex::operator-(complex& a,complex &e) {
    return complex(real - a.real+e.real, imag - a.imag+e.imag);
}
int main() {
    complex a(4.0, 6), b(5, 9), c,e(1,2);
    c = a - b-e;
    cout << c.real << "," << c.imag << endl;
    cout << (a + b).real << "," << (a + b).imag << endl;
}


  • 写回答

2条回答 默认 最新

  • 关注

    二元运算符,作为成员函数,被自身对象调用,所以当括号有两个参数,加上自身就是3个参数了。如果非要用两个参数,请用友元函数。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • 旺仔不爱牛奶 2022-04-08 20:09
    关注
    
    #include <iostream>
    using namespace std;
    class complex {
    public:
        double real, imag;
        complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {}
        complex operator-(complex& a);
    
    };
    complex operator+(complex& b, complex& c) {
        return complex(b.real + c.real, b.imag + c.imag);
    }
    complex complex::operator-(complex& a) {
        return complex(this->real - a.real,this->imag - a.imag);
    }
    int main() {
        complex a(4.0, 6), b(5, 9), c, e(1, 2);
        c = a - b - e;
        cout << c.real << "," << c.imag << endl;
        cout << (a + b).real << "," << (a + b).imag << endl;
    }
    
    
    
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月17日
  • 已采纳回答 4月9日
  • 创建了问题 4月8日

悬赏问题

  • ¥15 Matlab计算100000*100000的矩阵运算问题:
  • ¥50 VB6.0如何识别粘连的不规则的数字图片验证码
  • ¥16 需要完整的这份订单所有的代码,可以加钱
  • ¥30 写一个带界面控制的机房电脑一键开机关机并且实时监控的软件
  • ¥15 Stata数据分析请教
  • ¥15 请教如何为VS2022搭建 Debug|win32的openCV环境?
  • ¥15 关于#c++#的问题:c++如何使用websocketpp实现websocket接口调用,求示例代码和相关资料
  • ¥15 51单片机的外部中断,按下按键后不能切换到另一个模式
  • ¥15 java连接sqlserver有问题
  • ¥15 yolov8 如何调cfg参数