类的友元分为友元函数和友元类
1.
首先为什么要引入友元这个概念?
C++提供了很好的封装性,但是也有很多代价,就是效率降低,因为每次都要调用成员函数访问内部的数据就导致了调用开销很大,因此设置友元这一概念。
友元函数
class Point
{
private:
double X;
double Y;
public:
Point(double xi, double yi)
{
X = xi;
Y = yi;
}
double GetX()
{
return X;
}
double GetY()
{
return Y;
}
friend double Distance(Point& a, Point& b);
};
double Distance(Point& a, Point& b)
{
double dx = a.X - b.X;
double dy = a.Y - b.Y;
return sqrt(dx*dx + dy * dy);
}
int main()
{
Point p1(3.0, 5.0), p2(4.0, 6.0);
double d = Distance(p1, p2);
cout << "The distance is" << d << endl;
system("pause");
return 0;
}
这段代码体现了友元函数的一个特点,可以直接访问对象的私有成员,在c++前期我们经常是调用成员函数来完成对于类私有数据的改变,但是在这里我们看到声明为友元函数的时候友元函数可以直接访问类的私有成员。
语法其实很好掌握,就是在函数返回值类型前面加上一个关键字friend。
需要注意:友元破坏了封装性,并且友元函数不是类的成员,所以在友元函数中没有this指针
友元类
class A
{
private:
int a;
public:
friend class B;
};
来看一个简单的代码,若一个类是另一个类的友元,则此类的所有成员函数都能访问对方类的私有成员。
在经过上述声明后**,类B是类A的友元类,但是类A不是类B的友元类**。
有了友元类,我们就可以很轻易的建立链表结构。
我们来看个单链表在C++中的建立。
使用了友元类
class A
{
private:
int a;
public:
friend class B;
};
class node
{
private:
int data;
node* next;
public:
node(int d, node* n = 0)
{
data = d;
next = n;
}
friend class list;
};
class list
{
private:
node* head;
node* tail;
size_t length;
public:
list()//拷贝构造函数
{
head = 0;
tail = 0;
}
~list()
{
while (head)
{
node* temp = head;
head = head->next;
delete temp;
}
}
void push_bank(int x)
{
if (length == 0)
{
node* p = new node(x);
head = tail = p;
}
else
{
node* p = new node(x);
tail->next = p;
tail = p;
}
length++;
tail->next = NULL;
}
void pop_bank(int x)
{
if (length == 0)
{
node* p = new node(x);
head = tail = p;
}
else
{
node*p = new node(x);
p->next = head;
head = p;
}
length++;
}
void ListShow()
{
node *q = head;
while(q)
{
cout << q->data << "-->";
q = q->next;
}
}
};
int main()
{
list mylist;
mylist.pop_bank(1);
mylist.pop_bank(2);
mylist.pop_bank(3);
mylist.ListShow();
system("pause");
return 0;
}
函数功能上面暂且实施头尾插,我们可以看到,当这个类list是这个类node的友元类的时候,这时候list类里面就可以对node里面的成员进行直接访问,友元类的直接函数也可以像友元函数那样直接访问改类的所有成员。