友元函数实现复数类操作

#include <iostream>
using namespace std;
class myComplex
{
private:
	double real, imag;
public:
	myComplex();
	myComplex(double r,double x);
	friend myComplex addCom(myComplex c1, myComplex c2);
	//两个参数对象c1 与 c2相加
	friend void outCom(myComplex c);
};
myComplex::myComplex()
{
	real = 0;
	imag = 0;
}
myComplex::myComplex(double r, double i)
{
	real = r;
	imag = i;
}
myComplex addCom(myComplex c1, myComplex c2)
{
	return myComplex(c1.real + c2.real, c1.imag + c2.imag);
}
void outCom(myComplex c)
{
	cout << "(" << c.real << "," << c.imag << ")";
}
int main()
{
	myComplex c1(1, 2), c2(3, 4), res;
	res = addCom(c1, c2);//调用友元函数不通过类对象
	outCom(c1);
	cout << "+";
	outCom(c2);
	cout << "=";
	outCom(res);
	cout << endl;
	return 0;
}

运行结果:
友元函数实现复数类操作

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
C++

友元函数声明3-14

2023-10-17 17:27:51

C++

友元类示例

2023-10-18 19:56:42

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索