友元类示例

#include <iostream>
using namespace std;
class myComplex {
private:
	double real, imag;
public:
	myComplex();
	myComplex(double r, double i);
	friend class oper;
};
myComplex::myComplex()
{
	real = 0;
	imag = 0;
}
myComplex::myComplex(double r, double i)
{
	real = r;
	imag = i;
}
class oper
{
public:
	myComplex addCom(myComplex c1, myComplex c2); //成员函数
	//两个参数对象 c1与c2相加
	void outCom(myComplex c);
	//输出参数对象c的有关数据
};
myComplex oper::addCom(myComplex c1, myComplex c2)
{
	return myComplex(c1.real + c2.real, c1.imag + c2.imag);
}
void oper::outCom(myComplex c)
{
	cout << "(" << c.real << "," << c.imag << ")";
}
int main()
{
	myComplex c1(3, 4), c2(5, 6), res;
	oper o;
	res = o.addCom(c1, c2);
	o.outCom(c1);
	cout << "+";
	o.outCom(c2);
	cout << "=";
	o.outCom(res);
	cout << endl;
	return 0;
}

运行结果:
友元类示例

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

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

友元函数实现复数类操作

2023-10-18 19:04:13

C++

友元程序填空题

2023-10-18 20:20:47

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