C++类与对象(三)---友元、内部类

友元

由于我们对成员变量都要进行封装,我们想要用封装后的成员变量时编译器就会报错,为了满足这一需求就产生了友元。

class A
{
	friend class B;//友元标识
private:
	int _a;
	int _b;
};

class B
{
public:

	void fun(const A&a)
	{
		cout << a._a << endl;
	}
private:
	int i;
};

B类就可以访问A类中的私有成员。

因为cout的输出流对象和隐含的this指针在抢占第一个参数的位置。this指针默认是第一个左操作数,而实际上cout需要的是第一个形参列表,所以我们将<<重载为全局函数,而全局函数无法访问类内成员变量,所以就需要定义operator <<为友元。

class Date
{
 friend ostream& operator<<(ostream& _cout, const Date& d);
 friend istream& operator>>(istream& _cin, Date& d);
public:
    Date(int year, int month, int day):_year(year)
		                              ,_month(month)
		                              ,_day(day)
	{}

private:
	int _year;
	int _month;
	int _day;
};

ostream& operator<<(ostream& _cout, const Date& d)
{
	_cout << d._year << d._month << d._day << endl;
	return _cout;
}

istream& operator>>(istream& _cin, Date& d)
{
	_cin >> d._year;
	_cin >> d._month;
	_cin >> d._day;
}

内部类

内部类就是在一个类里面创建的类,如下代码B就是A的一个内部类,其天生就是A的友元而A不是B的友元

class A {
public:

	class B {
	public:
		void fun(const A& a) {
			cout << a.b << endl;
			cout << _b << endl;
		}
	private:
		int _b;
	};

private:
	int b;
};

//B是A的友元,A不是B的友元

int main() {
	A a;
	A::B b; //只能加访问限定符来访问B
	b.fun(a);

	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值