友元(Friend)
友元函数(Friend Function)
But C++ also provides another of function to access members in class friend functions
– friend functions are not member functions but can still access class private members
– defined outside of class scope
– to access private members of two or more different classes
– for I/O or operator functions
– placed inside the class definition and preceded by the friend keyword
– defined outside the class as a normal, nonmember function
– called like a normal non-member function.
If a function is a friend of two or more different classes, each class must contain the friend function prototype within its body.
A friend function cannot be inherited but can be a member of one class.
注意。
1. 类内声明(要加friend修饰词),类外定义(不能加friend修饰词)
2. 不能被继承。
3. 友元函数不是成员函数!使用的时候,一定不能写 obj1.myFriendFun1();!因为不是成员函数!点不出来的!
友元类(Friend Classes)
An entire class can be a friend of another class
– can be used when all member functions of one class should access the data of another class
– require prototypes to be placed within each class individually
An entire class can be designed as friend
– all its member functions automatically granted a friendship by the class
– but “class B is a friend of class A” does not imply “class A is a friend of class B”
//in CPoint.h
class CPoint {
friend class CLine; // 我(CPoint)把你(CLine)当朋友,你就可以取到我的东西
int x, y;
void Offset(int diff) {
x += diff; y += diff;
}
public:
CPoint() { x=0; y=0; }
CPoint(int a, int b) { x=a; y=b; }
void set(int a, int b) {
x=a; y=b;
} void Print() {
cout << x << “ ” << y << endl;
}
};
//in CLine.h
class CLine {
CPoint p1, p2;
public:
CLine(int x, int y, int w, int z) {
p1.x = x; p1.y = y; //access private
p2.x = w; p2.y = z; }
void Print()() {
//call public Print in CPoint
cout << “Point 1:”; p1.Print();
cout << “Point 2:”; p2.Print(); }
void Display() {
offset(p1,100); //call friend func
p2.Offset(200); //call private func
Print(p1, p2); }
};
友元类,好像现在看起来,发明者提供这种写法,好像也只是为了让代码的写作更加简单……
e.g. A为了访问B中的成员变量,就用set和get不就好了吗……
嵌套类(Nested Class)
感觉有点像内部类。我在做Android开发的时候,还遇到过匿名内部类……
e.g. xxxButton.setOnClickListener(new xxxListener() {
@override
void xxxOnClick(Event e) {
xxx;
}
});
这种…也不知道记错没有……感觉好像是这样…………
Nested class cannot access any private member of the outer class by default.
嵌套类默认情况下,不能访问外部的类的私有成员。但,可以用friend解决。
e.g. 在外部类A中声明嵌套类B是它的朋友,friend class B;
Inner class is not visible globally.
A nested class CTwo in COne can have the same kind of members as a nonnested class.
链表的定义,一种递归的定义。
class Chain { //outer class
public:
class Item { //all members are private
friend class Chain;
Item(int val = 0); //constructor
Item *next; //point to its own class
int val;
};
//...
private:
Item *chain;
Item *at_end;
};
注意,在List中,这个Item * next不是自己指向自己,而是说,可以指向这个相同class的实例!
(当然,也可以自己指向自己…)