重载运算符的错误

本文探讨了C++中运算符重载的概念,并通过具体的代码示例解释了成员函数进行运算符重载时只能有一个参数的原因。同时展示了如何正确地实现复数类中的加法和减法运算符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 在用成员函数进行运算符重载时,只能有一个参数。否则出现错误:must take either zero or one argument;


2.错误:

#include<iostream>
using namespace std;

class Complex
{
	public:
		Complex(int r, int i){real=r; ima=i;}
		int getR(){return real;}
		int getI(){return ima;}
		void display(){cout<<real<<" + "<<ima<<"i"<<endl<<endl;}
		friend Complex operator + (Complex&, Complex&);
		friend Complex operator - (Complex&, Complex&);

	private:
		int real;
		int ima;
};
Complex Complex::operator + (Complex& a, Complex& b)<span style="white-space:pre">		</span>//error!
{
	int r=a.getR()+b.getR();
	int i=a.getI()+b.getI();
	Complex c(r, i);
	return c;
}
Complex Complex::operator - (Complex& a, Complex& b)<span style="white-space:pre">		</span>//error!
{
	int r=a.getR()-b.getR();
	int i=a.getI()-b.getI();
	Complex c(r, i);
	return c;
}

int main()
{
	Complex a(3,5);	a.display();
	Complex b(7,7); b.display();

	Complex c=a+b;	
	cout<<"a+b=\n"; c.display();
	Complex d=a-b;
	cout<<"a-b=\n"; d.display();
	
	return 0;
}
错误同1. 因加了Complex类的域名变成成员函数,而非友元函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值