friend.cpp

来自「c语言教程源码」· C++ 代码 · 共 65 行

CPP
65
字号
//这个程序在本书所带软盘中。文件名为FRIEND.CPP
//这个程序演示怎样在类中定义友元,使它们可以访问类的私有成员。

#include <iostream.h>

class example
{
	// 友元子程序表
	friend float add(example&, example&);
	friend float sub(example&, example&);

	private:
		float real1;
		float real2;
  	public:
		example(float, float);			//构造函数
		void display();

};

example::example(float r1 = 0, float r2 = 0)
{
	real1 = r1;
	real2 = r2;
}
void example::display()
{
	cout << "两个实数是: " << real1 << "  " << real2 << endl;
}

//编写友元子程序
float add(example &obj1, example &obj2)
{
	obj1.real1 = 9.8; obj2.real1 = 1.6;	//改变私有成员数据
	return(obj1.real1 + obj2.real1);	//访问私有成员数据并返回其和
}

float sub(example &obj1, example &obj2)
{
	obj1.real2 = 1.8; obj2.real2 = 6.6;
	return(obj1.real2 - obj2.real2);
}

void main(void)
{
	example object1(3.2, 5.6), object2(1.1, 8.4);
	float sum, difference;

	object1.display();
	object2.display();

	sum = add(object1, object2);
	difference = sub(object1 ,object2);

	cout << "\n对象 1 中的第一个数和对象 2 中的第一个数的和是: " << sum << endl;
	cout << "对象 1 中的第二个数和对象 2 中的第二个数的差是: " << difference << endl;
}

/*这个程序运行后将显示如下输出结果:
两个实数是: 3.2  5.6
两个实数是: 1.1  8.4

对象 1 中的第一个数和对象 2 中的第一个数的和是: 11.4
对象 1 中的第二个数和对象 2 中的第二个数的差是: -4.8
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?