Home >Backend Development >C++ >Detailed explanation of C++ friend functions: Application of friend functions in object-oriented design?
C A friend function is a special function that provides access to private and protected members of another class. Non-member functions can interact with a specific class by declaring friend functions. Applications of friend functions include operator overloading, I/O operations and underlying implementation. For example, friend functions can be used to overload operators to support operations between custom data types, as shown in the following case: class Vector { public: friend Vector operator (const Vector& v1, const Vector& v2); };
C Detailed explanation of friend functions: Application in object-oriented design
What is a friend function?
In C, a friend function is a special function that is granted access to private and protected members of another class. This allows non-member functions to interact with a specific class without having to be declared as a member function of the class.
How to declare a friend function?
There are two ways to declare friend functions:
class MyClass { friend void myFriendFunction(); };
friend
Keyword declaration: class MyClass; // 前向声明 void myFriendFunction() { MyClass obj; // 访问 MyClass 的私有成员 }
Application of friend function
Friend Functions have many applications in object-oriented design, including:
and *
to support operations between custom data types. dc01603f162e8bccf508736ba29c0229>
, to simplify object serialization. Practical Case: Operator Overloading
The following code example shows how to use friend functions to overload the
operator to support Addition of two Vector
objects:
class Vector { int x, y; public: Vector(int _x, int _y) : x(_x), y(_y) {} friend Vector operator+(const Vector& v1, const Vector& v2); }; Vector operator+(const Vector& v1, const Vector& v2) { return Vector(v1.x + v2.x, v1.y + v2.y); } int main() { Vector v1(1, 2), v2(3, 4); Vector v3 = v1 + v2; // 使用重载的 + 运算符 return 0; }
In the above example, the operator
function is a friend function that allows non-member functions to access the Vector
Private data members of the class x
and y
.
The above is the detailed content of Detailed explanation of C++ friend functions: Application of friend functions in object-oriented design?. For more information, please follow other related articles on the PHP Chinese website!