Home  >  Article  >  Backend Development  >  Can friend functions call other friend functions?

Can friend functions call other friend functions?

王林
王林Original
2024-04-15 22:45:01318browse

Friend functions can call each other. A friend function is a special function that has access to private member variables and private methods of a class, allowing the creation of closely related groups of functions that can access each other's private data. Friend functions can call each other like ordinary functions.

Can friend functions call other friend functions?

#Can friend functions call each other?

Friend function is a special function in C that can access private member variables and private methods of a class. The word , as the name suggests, means having a friendly relationship. So, can friend functions call each other?

The answer is yes.

Friend functions can call each other, which is one of the strengths of friend functions. It allows us to create a set of closely related functions that can access each other's private data.

Syntax

The syntax for declaring a friend function to call another friend function is similar to that of a normal function call. For example:

class MyClass {
    friend void func1();
    friend void func2();
};

void func1() {
    func2(); // 调用友元函数 func2
}

Practical case

The following is a simple example of using friend functions to call each other:

#include <iostream>

class ComplexNumber {
    private:
        double real, imag;

    public:
        ComplexNumber(double r, double i) : real(r), imag(i) {}

        // 以下声明为友元函数
        friend std::ostream& operator<<(std::ostream&, const ComplexNumber&);
        friend bool operator==(const ComplexNumber&, const ComplexNumber&);
};

// 友元函数重载运算符 <<
std::ostream& operator<<(std::ostream& os, const ComplexNumber& z) {
    os << z.real << " + " << z.imag << "i";
    return os;
}

// 友元函数重载运算符 ==
bool operator==(const ComplexNumber& z1, const ComplexNumber& z2) {
    // 友元函数可以访问私有成员变量 real、imag
    return z1.real == z2.real && z1.imag == z2.imag;
}

int main() {
    ComplexNumber z1(1.2, 3.4), z2(1.2, 3.4);

    std::cout << z1 << " == " << z2 << " : " << std::boolalpha << (z1 == z2) << std::endl;

    return 0;
}

Output

1.2 + 3.4i == 1.2 + 3.4i : true

In this example, the friend functions operator and <code>operator== can call each other to overload the operator and <code>==.

The above is the detailed content of Can friend functions call other friend functions?. 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