C++ OOP的复数实现 《C++多线程编程实战》

本文介绍了一个使用C++实现的复数类,该类通过运算符重载实现了复数的加法操作,并利用随机数生成复数实例进行演示。文章详细展示了如何定义复数类,包括成员变量和构造函数,以及如何通过友元函数重载加法运算符,最后在主函数中创建复数对象并执行加法操作。

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

#include <iostream>

using namespace std;

double Rand(double dMin, double dMax)
{
	double dVal = (double)rand() / RAND_MAX; //产生0~1之间的数
	return dMin + dVal * (dMax - dMin);
}

class CComplex
{
public:
	CComplex()
	{
		dReal = Rand(-10, 10);
		dImg = Rand(-10, 10);
	}
	CComplex(double dReal, double dImg)
	{
		this->dReal = dReal;
		this->dImg = dImg;
	}
	friend CComplex operator+ (const CComplex& c1, const CComplex& c2);
	friend ostream& operator<< (ostream& os, const CComplex& c);
private:
	double dReal;
	double dImg;
};

CComplex operator+ (const CComplex& c1, const CComplex& c2)
{
	CComplex c(c1.dReal + c2.dReal, c1.dImg + c2.dImg);
	return c;
}

ostream& operator<< (ostream& os, const CComplex& c)
{
	return os << c.dReal << "+" << c.dImg << "i";
}

int main(int argc, char* argv[])
{
	CComplex c1;
	CComplex c2(-2.3, 0.9);
	CComplex c = c1 + c2;

	cout << c << endl;
    return 0; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值