📜  C++中静态函数和友元函数的区别

📅  最后修改于: 2021-09-12 11:10:13             🧑  作者: Mango

静态函数基本上是一个成员函数,即使类的对象没有初始化也可以调用。这些函数与任何对象相关联,用于在类的不同对象之间维护类成员函数的单个副本。这个函数用static关键字表示。

Friend 函数 它基本上是访问类的非公共成员特别需要的函数。它有权访问该类的所有私有成员和受保护成员。它通常提供一些类通常不使用的附加功能,并允许非成员函数共享提供类信息。

静态函数和友元函数之间的表格区别

Static Function

Friend Function

It is a member function of a class that is called even when the object of the class is not initialized. It is a function that is declared outside the class scope.
In this, it cannot access any variable of its class except for static variables. In this, it can access private and public members of the class.
It is denoted by placing a static keyword before the function name. It is denoted by placing a friend keyword before the function name.
This function is generally used to make function members independent of any particular object of the class. This function is generally used to access non-public members of the class.
These functions are normally used when one wants a function that is the same for every instance of the class.  These functions are normally used to share information of class that was hidden previously.
It can have access to members of one class.   It can have access to members of several classes.  
It cannot be used when one needs to overload operators.   It can be used when one needs to overload operations because overloading operators can only be done through friends or non-static members.  
It can also be used if the function has no need to read, change or modify the state of a particular instance of the class or if one needs to use function pointer to a member function of class.   It can also be used when one wants to create code that not a member of the class and should not be a member of their class.  
This function can be hidden behind privileges.   This function cannot be hidden and anyone may call the friend function.  
It is associated with class and not an object.   It is declared in class but does not belong to the class.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程