C++友元函数(friend)

类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员和公有(public)成员。

尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是类的成员函数。

	class Box
	{
		double width;
		//友元函数的原型,在private,public,protected下定义都可以
		friend void showBox(Box b);
	public:
		double height;
		void setWidth(double width);
		
	};
	
	void Box::setWidth(double width)
	{
		this->width = width;
	}
	
	//友元函数的定义
	void showBox(Box b)
	{
		cout << b.width << endl;
	}
	
	int main()
	{
		Box box;
		box.setWidth(12.3);
	
		//调用
		showBox(box);
		return 0;
	}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43340991/article/details/86660385
今日推荐