友元函数

本文深入解析C++中的友元函数概念,包括其声明与定义方式,如何通过友元函数访问类的私有成员,以及友元函数在运算符重载中的应用。同时,通过实例演示了友元函数在时间和点坐标类中的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

友元函数
形式:
friend 类型名 友元函数名(形参表);
然后在类体外对友元函数进行定义,定义的格式和普通函数相同,但可以通过对象作为参数直接访问对象的私有成员
说明如下:
1)必须在类的说明中说明友元函数,说明时以关键字friend开头,后跟友元函数的函数原型,友元函数的说明可以出现在类的任何地方,包括在private和public部分;
2)注意友元函数不是类的成员函数,所以友元函数的实现和普通函数一样,在实现时不用"::“指示属于哪个类,只有成员函数才使用”::"作用域符号;
3)友元函数不能直接访问类的成员,只能访问对象成员,
4)友元函数可以访问对象的私有成员,但普通函数不行;
5)调用友元函数时,在实际参数中需要指出要访问的对象,
6)类与类之间的友元关系不能继承。
7)一个类的成员函数也可以作为另一个类的友元,但必须先定义这个类。

具体可搜百度百科 友元函数

#include <iostream>
#include <iomanip>
using namespace std;
class point
{
 	int x;
 	int y;
public:
  	void set(int a,int b)
 	 {
 		  x=a;y=b;
	  } 
  	void print()const
  	{
		  cout<<"("<<x<<","<<y<<")\n";
  	}
	  friend point operator+(const point &a,const point &b);//友元 
	  /*重载二维运算符的函数参数需要const,因为函数要保证实参的值不能被修改,需要加const限制*/
 	 friend point add(const point &a,const point &b);//友元 
};
	point operator+(const point &a,const point &b)
	{
 	point s;
	 s.set(a.x+b.x,a.y+b.y);
 	return s;
	} 
	point add(const point &a,const point &b)
	{
	 point s;
	 s.set(a.x+b.x,a.y+b.y);
	 return s;
	}
int main(int argc, char *argv[])
{
	 point a,b;
	 a.set(3,2);//
	 b.set(1,5);
	 (a+b).print();
	 operator+(a,b).print();
	 add(a,b).print();
	 return 0;
}
/*(4,7)
(4,7)
(4,7)*/ 

再举一个例子
时间加一秒

#include <iostream>
#include <iomanip>
using namespace std;
class Time
{
 	int hour,minute,second;
public:
	 void set(int h,int m,int s)
	 {
		  hour=h;minute=m,second=s;
	 }
	 friend Time &operator++(Time &a);
	 /*Time &operator++()
 	{
		 if(!(this->second=(this->second+1)%60)&&!(this->minute=(this->minute+1)%60))
 		 this->hour=(this->hour+1)%24;
		 return *this;
	 }//成员函数,比较不同this 与 a*/
	 friend Time operator++(Time &a,int);
	 friend ostream &operator<<(ostream &o,const Time &t);
};
	Time &operator++(Time &a)
	{
		 if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
		  a.hour=(a.hour+1)%24;
 		return a;
	}
	Time operator++(Time &a,int)
	{
		 Time t(a);
		 if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
  		a.hour=(a.hour+1)%24;
		 return a;
	}
	ostream &operator<<(ostream &o,const Time &t)
	{
	 o<<setfill('0')<<setw(2)<<t.hour<<":"<<setw(2)<<t.minute<<":";
	 return o<<setw(2)<<t.second<<"\n"<<setfill(' ');
	}
int main(int argc, char *argv[])
{
 	Time t;
	 t.set(11,59,58);
	 cout<<t++;//时间t++函数  
	 cout<<++t;//在上一个基础上 时间++t函数 
	 return 0;
}
/*
11:59:59
12:00:00
*/ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值