问题
I have a doubt related to friend functions in C++. Friend function is not a member function of the claas and can be invoked directly from the main. So, what difference does it make if we keep the friend
function within the private
or the public
part of the class
. I have generally noticed that the friend
functions are always in the public part. In what scenario we should keep the friend
function within private
.
回答1:
The compiler does not pay any attention to whether a friend function is in the private or public (or protected) section of a class. Most people put it in the public section, but it'll be publicly visible regardless of where you put it.
回答2:
It does not matter if you declare it in the public:
or private:
part of the class. It will function the same regardless.
回答3:
One reason for having the friend declarations in the private
section is that it can keep them together with the member functions or objects they are supposed to have access to.
Other than that, there is no difference.
回答4:
The friend
keyword is just here to grant private
access to another function which is not part of your class. Since it's not part of your class, it's not affected by public/private
specifiers.
回答5:
it doesn’t matter where you put the friendship declaration. It may exists inside any of the class parts (public, private or protected) but must be put outside any function or aggregate.
Here is a nice example and explanation from www.cprogramming.com:
It is often useful for one class to see the private variables of another class, even though these variables should probably not be made part of the public interface that the class supports. For instance, if you were writing a binary tree, you might want to use a Node class that has private data, but it would still be convenient for the functions that actually combine nodes together to be able to access the data directly without having to work through the Node interface. At times, it may not even be appropriate for an accessor function to ever give even indirect access to the data.
来源:https://stackoverflow.com/questions/11107829/friend-functions-in-c