友元函数:
在类里的声明一个普通的函数,加上关键字friend,就成了该类的友元函数,它可以访问该类的一切成员,其原型为:
friend<类型><友元函数名>(<参数表>);
友元函数声明的位置可以在类的任何地方,public,protect,private;
class Point
{
public:
Point(double xi, double yi){ X = xi, Y = yi; }
friend double length(Point &a, Point &b);
private:
double X, Y;
};
class Point
{
public:
Point(double xi, double yi){ X = xi, Y = yi; }
private:
friend double length(Point &a, Point &b);
double X, Y;
};
友元函数不是类定义的函数,但它的特性是可以访问类的private成员;
double length(Point &a, Point &b)
{
double dx = a.X - b.X;
double dy = a.Y - b.Y;
return dx + dy;
}
*******特别注意---友言函数的使用在main函数之前,这里务必注意函数名与friend的是否一致,编译器不会报错告诉你名字出错了!只会告诉你无法访问private的成员变量!
友元类
除函数之外,一个类也可以被声明为另一个类的友元,该类称为友元类。
友元类的声明格式为: friend class <类名>
class student
{
public :
friend class teacher;
student(){};
private:
int number, score;
};
class teacher
{
public :
teacher(int i, int j);
void display();
private:
student a;
};
teacher类是student类的友元类,teacher类所有的成员函数都可以访问类中student类的任意成员!
teacher 类的成员display()引用了student类的两个私有成员number和score
teacher::teacher(int i, int j)
{
a.number = i;
a.score = j;
}
void teacher::display()
{
cout << "No= " << a.number << " ";
cout << "score =" << a.score << endl;
}
经典示例:
#include<iostream>
using namespace std;
class Ruler;
class Book
{
public:
Book(){ weight = 0; }
Book(double x)
{
weight = x;
}
friend double tatalweight( Book &a, Ruler &b);
private:
double weight;
};
class Ruler
{
public:
//friend class Book;
Ruler(){ weight = 0; }
Ruler(double x)
{
weight = x;
}
friend double tatalweight( Book &a, Ruler &b);
private:
double weight;
};
double tatalweight(Book &a, Ruler &b)
{
return a.weight + b.weight;
}
int main()
{
Book a(5);
Ruler b(5);
std::cout << "总重量为:" << tatalweight(a, b) << std::endl;
system("pause");
return 0;
}