复数运算(友元函数)

本文介绍了如何在C++中实现一个复数类,包括构造函数、友元函数addCom和minusCom用于复数加减运算,以及友元函数outCom用于输出复数的实部和虚部。在main函数中展示了如何通过这些函数进行连续的复数运算并输出结果。

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

题目描述

复数类的声明如下:


class Complex
{
private:
	double real; // 实部
	double imag; // 虚部
public:
	Complex();
	Complex(double r, double i);
	// 友元函数,复数c1 + c2(二参数对象相加)
	friend Complex addCom(const Complex& c1, const Complex& c2);
	// 友元函数,输出类对象c的有关数据(c为参数对象)
	friend void outCom(const Complex& c);
};

要求如下:

1.     实现复数类和友元函数addCom和outCom。

2.   参考addCom函数为复数类增加一个友元函数minusCom,用于实现两个复数的减法

3.     在main函数中,通过友元函数,实现复数的加减法和复数的输出。

输入

10 10
3
+ 20 10
- 15 5
+ 5 25

 

第1行:第1个复数的实部和虚部

第2行:需进行运算的次数,注意:是连续运算。具体结果可参考样例

    第3行开始,每行输入运算类型,以及参与运算的复数的实部与虚部。“+”表示复数相加,“-”表示复数相减。

输出

(30,20)
(15,15)
(20,40)
 

 每行输出复数运算后的结果,复数输出格式为“(实部,虚部)”。

#include <iostream>
using namespace std;

class complex {
	private:
		double real; // 实部
		double imag; // 虚部
	public:
		complex();
		complex(double r, double i);
		// 友元函数,复数c1 + c2(二参数对象相加)
		friend complex addCom(const complex &c1, const complex &c2);
		friend complex minusCom(const complex &c1, const complex &c2);
		// 友元函数,输出类对象c的有关数据(c为参数对象)
		friend void outCom(const complex &c);
};

complex::complex(double r, double i) {
	this->real = r;
	this->imag = i;
}

complex::complex() {
	this->imag = 0;
	this->real = 0;
}
//返回类型为complex的函数
complex addCom( const complex &c1, const complex &c2) {
	complex temp;
	temp.real = c1.real + c2.real;
	temp.imag = c1.imag + c2.imag;
	return temp;
}
//返回类型为complex的函数
complex minusCom( const complex &c1, const complex &c2) {
	complex temp;
	temp.real = c1.real - c2.real;
	temp.imag = c1.imag - c2.imag;
	return temp;
}

void outCom(const complex &c) {
	cout << '(' << c.real << ',' << c.imag << ')' << endl;
}
//友元函数最好不要修改原对象的内容,因此最好重新返回一个对象
int main() {
	double r, i;
	cin >> r >> i;
	complex c(r, i);
	int t;
	cin >> t;
	complex temp = c; //
	for (int i = 0; i < t; i++) {
		double r1, i1;
		char ch;
		cin >> ch >> r1 >> i1;
		complex c1(r1, i1);
		if (ch == '+') {
			temp = addCom(temp, c1);
			outCom(temp);
		} else if (ch == '-') {
			temp = minusCom(temp, c1);
			outCom(temp);
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值