Definition of friend class and accessor sections
When defining a class as a friend class, does it matter in which accessor section the definitions is placed, and if so d开发者_JS百科oes that change the members the friend has access to?
class aclass
{
private:
// friend bclass;
public:
// friend bclass;
protected:
// friend bclass;
};
class bclass
{};
Access specifiers do not apply to friend function/Class
You can declare the Friend Function or Class under any Access Specifier and the Function/Class will still have access to all the member variables(Public,Protected & Private) of that Class.
Once you place friend class/function inside a given class (say 'aclass') anywhere. It will have access to all defined members of the class (irrespective of public/private/protected); for example:
class aClass
{
public: int pub; void fun1() {}
protected: int pro; void fun2() {}
private: int pri; aClass(const aClass& o);
friend void outsider ();
};
Friend function outsider() can access pub, pro, pri, fun1, fun2; but not aClass copy constructor in this case (if it's not defined anywhere).
Friend functions aren't placed inside any accessors by convention, because by definition they aren't part of the class. You might do something like this:
class Elephants
{
//friend void notAMemberFuncion(argument 123);
public:
// member functions;
protected:
// data members;
};
The friend class/function can access all the private/protected/public members of class, which access section the friend class/function is placed doesn't make any difference. It's suggested to put friend class/function in the public section, because friends is part of the class interface.
精彩评论