每天学点C++之类与对象(2)——友元

首先,什么是友元呢?大家知道类的私有成员变量在类外是无法访问的,可是在某些特殊时候我们需要在类外访问那我们就可以使用友元。

友元的关键字是friend

一 全局函数作为友元

#include<iostream>
using namespace std;
class Circle {
	friend void getPot(Circle c);
public:
	static int num;//圆的数量
	Circle(int x1, int y1, double r1):x(x1), y(y1), r(r1){}
	static void setNum(int num1) {
		num = num1;
	}
	int getRadius() const {
		r += 1;
		return r;
	}
private:
	int x, y;//圆的坐标
	mutable double r;//圆的半径

};
void getPot(Circle c) {
	cout << "(" << c.x << "," << c.y << ")" << endl;
}
int Circle::num = 0;
int main() {
	Circle x(0, 0, 2);
	getPot(x);
}

这里我们在类内声明了全局函数getPot(Circle c)是该类的友元从而使得在类外的函数可以访问类内的私有成员变量。

二 友元类

我们还可以将一个类声明为另一个类的友元,这样该类的所有成员函数都可以访问另一个类的私有成员变量。这就好比你把你家的大门钥匙交给了你自己信得过的朋友。

#include<iostream>
using namespace std;
class Circle {
	friend class Pot;
public:
	static int num;//圆的数量
	Circle(int x1, int y1, double r1):x(x1), y(y1), r(r1){}
	static void setNum(int num1) {
		num = num1;
	}
	int getRadius() const {
		r += 1;
		return r;
	}
private:
	int x, y;//圆的坐标
	mutable double r;//圆的半径

};
class Pot{
public:
	void getPot(Circle x) {
		cout << "(" << x.x << "," << x.y << ")" << endl;
	}
};

int Circle::num = 0;
int main() {
	Circle x(0, 0, 2);
	Pot pot;
	pot.getPot(x);
}

三 成员函数作为友元

当我不想让一个类中所有成员函数都能够访问另一个类的私有成员变量的时候我们可以只设置有元函数,既然一个类都可以作为另一个类的友元那么类的成员函数自然也可以。

#include<iostream>
using namespace std;

class Circle;
class Pot {
public:
    void getPot(Circle x);
};

class Circle {
    friend void Pot::getPot(Circle x); // 正确的友元声明
public:
    static int num; // 圆的数量
    Circle(int x1, int y1, double r1) :x(x1), y(y1), r(r1) {}
    static void setNum(int num1) {
        num = num1;
    }
private:
    int x, y; // 圆的坐标
    mutable double r; // 圆的半径
};

void Pot::getPot(Circle x) { // Pot类的getPot函数
    cout << "(" << x.x << "," << x.y << ")" << endl;
}

int Circle::num = 0;

int main() {
    Circle x(0, 0, 2);
    Pot pot;
    pot.getPot(x);
}

大家一定要注意类和成员函数的声明之间的顺序关系,因为要在Circle中设置友元,所以在此之前要对该函数进行声明,而该函数是在另一个类里,所以该类最好写在Circle之前并在其中声明getPot()函数,在后面再进行声明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值