栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937904.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号