28 - Yugen's Embarrassing Ability
Friendship concept
- A relation in C++ of friend
- Friendships occur between functions and classes or between classes and classes
- Friendships are single-item and cannot be passed
Friend usage
- Declare friends with the friend keyword in a class
- Friends of a class can be other classes or concrete functions
- Friends are not part of the class
- Friends are not restricted by the access level in the class
- Friends have direct access to all members of a concrete class
friend syntax
- Declare a function or class with the friend keyword in a class
class Point { double x; double y; friend void func(Point& p); }; void func(Point& p) { }
[Example code] A preliminary study on the use of friends
#include <stdio.h> #include <math.h> class Point { double x; double y; public: Point(double x, double y) { this->x = x; this->y = y; } double getX() { return x; } double getY () { return y; } friend double func(Point& p1, Point& p2); }; double func(Point& p1, Point& p2) { double ret = 0; ret = (p2.y - p1.y) * (p2.y - p1.y) + (p2.x - p1.x) * (p2.x - p1.x); ret = sqrt (ret); return ret; } int main() { Point p1(1, 2); Point p2(10, 20); printf("p1(%f, %f)\n", p1.getX(), p1.getY()); printf("p2(%f, %f)\n", p2.getX(), p2.getY()); printf("|(p1, p2)| = %f\n", func(p1, p2)); return 0; }
Friend's embarrassment
- Friend was born to take into account the efficiency of the C language
- Friends directly destroy the object-oriented encapsulation
- Youyuan's high efficiency in actual products is not worth the loss
- Friendship has been gradually abandoned in modern software engineering
Precautions:
- Friendship is not transitive
- Friends of a class can be member functions of other classes
- A friend of a class can be a complete class, so all member functions are friends
[Example code] In-depth analysis of friends
#include <stdio.h> class ClassC { const char* n; public: ClassC(const char* n) { this->n = n; } friend class ClassB; }; class ClassB { const char* n; public: ClassB(const char* n) { this->n = n; } void getClassCName(ClassC& c) { printf("c.n = %s\n", c.n); } friend class ClassA; }; class ClassA { const char* n; public: ClassA(const char* n) { this->n = n; } void getClassBName(ClassB& b) { printf("b.n = %s\n", b.n); } /* void getClassCName(ClassC& c) { printf("c.n = %s\n", c.n); } */ }; int main() { ClassA A("A"); ClassB B("B"); ClassC C("C"); A.getClassBName(B); B.getClassCName(C); return 0; }