Home >Backend Development >C++ >The relationship between C++ friend functions and overloading

The relationship between C++ friend functions and overloading

WBOY
WBOYOriginal
2024-04-16 11:06:02518browse

Yes, friend functions can be overloaded. Like other functions, the overloaded friend function must have a different parameter list, such as the Vector3D class in the example, which has an overloaded friend function operator () and operator-(), which allows addition and subtraction operators to be applied to Vector3D objects.

C++ 友元函数与重载的关系

C The relationship between friend functions and overloading

Friend functions

Friend function is a special type of function that can access private members of other classes. In other words, it is not a member function of the class, but has the same access rights as a member function.

Define friend function:

class ClassName {
  // ...

  friend function_name();
};

Overloading

Overloading allows creation of the same name but with the same name in the same scope Multiple functions with different parameter lists. This means that when an overloaded function is called, the compiler will determine which function to call based on the arguments.

Interaction between friend functions and overloading

Friend functions can be overloaded. Like other functions, overloaded friend functions must have different parameter lists.

Practical case

Example class:

class Vector3D {
  double x, y, z;

public:
  Vector3D(double x, double y, double z) : x(x), y(y), z(z) {}

  friend Vector3D operator+(const Vector3D& lhs, const Vector3D& rhs);
  friend Vector3D operator-(const Vector3D& lhs, const Vector3D& rhs);
};

Overloaded friend function:

Vector3D operator+(const Vector3D& lhs, const Vector3D& rhs) {
  return Vector3D(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z);
}

Vector3D operator-(const Vector3D& lhs, const Vector3D& rhs) {
  return Vector3D(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}

Usage:

Vector3D v1(1, 2, 3), v2(4, 5, 6);

Vector3D v3 = v1 + v2;  // 调用重载的友元函数 operator+()
Vector3D v4 = v1 - v2;  // 调用重载的友元函数 operator-()

In this example, we define a Vector3D class and its overloaded friend function operator () and operator-(). These friend functions allow us to use addition and subtraction operators on Vector3D objects.

The above is the detailed content of The relationship between C++ friend functions and overloading. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn