📜  C++中友元函数和成员函数的区别

📅  最后修改于: 2021-09-11 03:50:21             🧑  作者: Mango

Friend 函数 它基本上是一个用于访问类的所有私有和受保护成员的函数。它被视为类的非成员函数,并由授予访问权限的类声明。该函数在声明中使用friend关键字作为前缀,如下所示:

使用友元函数定义类:

C++
class freetrial {
private:
    {
    public:
        {
            friend void check();
        }
        void check();
    }
}


C++
class freetrial {
private:
    {
    public:
        {
            void check();
        }
        trial::void check();
    }
}


成员函数:它基本上是一个可以声明为类成员的函数。它通常在类定义中声明并作用于同一个类的数据成员。它可以访问同一类的私有、公共和受保护的数据成员。该函数声明如下:

使用成员函数的类定义:

C++

class freetrial {
private:
    {
    public:
        {
            void check();
        }
        trial::void check();
    }
}

友元函数和成员函数的表格区别:

Friend Function

Member Function

It can be declared in any number of classes using the keyword friend. It can be declared only in the private, public, or protected scope of a particular class.
This function has access to all private and protected members of classes. This function has access to private and protected members of the same class.
One can call the friend function in the main function without any need to object. One has to create an object of the same class to call the member function of the class.
The Friend keyword is generally used to declare a function as a friend function. In these, there is no such keyword required.
It cannot be called using, can be invoked like a normal function without using an object, defined outside the class scope, etc. It has its own prototype within the class definition, operates on any object of the class, has access to all members of the class, etc.
This method provides access to provide and protected data members. This method provides modularity to a program.
It is generally used to modify or change private and protected data members of the class. It is generally used to improve code reusability and to make code maintainable.
It also provides additional functionality that is kept outside class, provides functions that need data, allows sharing private class information by non-member function, etc. It allows access to internal private data, can be used a general protocol or interface, use for internal purpose only, and non-publishable operations such as initialization and intermediate results of computation.
In this, the binary operation usually takes two explicit parameters. In this, binary operations usually take only one explicit parameter.
The unary operator takes at least one explicit parameter. The unary operator does not take any explicit parameter.
It is not a part of the class. It is a part of the class definition and is invoked by a particular object.