C++之友元

友元(使用的关键字是:friend)

作用:提高访问效率

1.友元函数可以直接访问类中的私有成员

#include <iostream>
#include <cmath>

using namespace std;

class Point{
	private:
		double x;
		double y;
	public:
		Point(double i = 10, double j = 20){
			x = i;
			y = j;
		}
		double getx(){
			return x;
		}
		double gety(){
			return y;
		}

		friend double dish2(Point &, Point &); //友元和类是同级关系
};

double dish1(Point &p1, Point &p2){
	double X = p2.getx() - p1.getx();
	double Y = p2.gety() - p1.gety();

	return sqrt(X*X + Y*Y);
}

double dish2(Point &p1, Point &p2){
	double X = p2.x - p1.x;
	double Y = p2.y - p1.y;

	return sqrt(X*X + Y*Y);
}

int main(int argc, const char *argv[])
{
	Point p1(2,5), p2(5, 9);
	cout << dish1(p1, p2) << endl;
	cout << dish2(p1, p2) << endl;

	return 0;
}

2.友元类可以访问另一个类的所有成员

#include <iostream>

using namespace std;

class A{
	private:
		int x, y;
	public:
		A(int i, int j){
			x = i;
			y = j;
		}
		int getx(void){
			return x;
		}
		int gety(void){
			return y;
		}
		
		friend class B;//声明B是A的友元类
};

class B{
	private:
		int z;
	public:
		B(int i = 0){
			z = i;
		}
		int add(const A& a){
			return a.x + a.y + z;
		}
		int sub(const A& a){
			return a.x - a.y - z;
		}
};

int main(int argc, const char *argv[])
{
	A a(1,2);
	B b(3);

	cout << b.add(a) << endl;
	cout << b.sub(a) << endl;
	
	return 0;
}

友元成员函数:一个类指定特定的函数访问另一个类中的成员

#include <iostream>

using namespace std;

class A;
class B{
	private:
		int z;
	public:
		B(int i = 0){
			z = i;
		}
		int add(const A&);
		int sub(const A&);
};
class A{
	private:
		int x, y;
	public:
		A(int i, int j){
			x = i;
			y = j;
		}
		int getx(void){
			return x;
		}
		int gety(void){
			return y;
		}
		
		friend int B::add(const A&);
};

int B::add(const A& a){
	return a.x + a.y + z;
}
int B::sub(const A& a){
	return a.x - a.y - z;
}

int main(int argc, const char *argv[])
{
	A a(1,2);
	B b(3);

	cout << b.add(a) << endl;
	cout << b.sub(a) << endl;//error
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值