友元函数
形式:
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
*/