友元类和访问器部分的定义
将类定义为友元类时,定义放置在哪个访问器部分是否重要?如果是,是否会更改友元可以访问的成员?
class aclass
{
private:
// friend bclass;
public:
// friend bclass;
protected:
// friend bclass;
};
class bclass
{};
When defining a class as a friend class, does it matter in which accessor section the definitions is placed, and if so does that change the members the friend has access to?
class aclass
{
private:
// friend bclass;
public:
// friend bclass;
protected:
// friend bclass;
};
class bclass
{};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
访问说明符不适用于友元函数/类
您可以在任何访问说明符下声明 Friend 函数或类,并且该函数/类仍然可以访问该函数/类的所有成员变量(公共、受保护和私有)班级。
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.
一旦您将友元类/函数放置在给定类(例如“aclass”)任何地方中。它将有权访问该类的所有已定义成员(无论公共/私有/受保护);例如:
Friend函数outsider()可以访问pub, pro, pri, fun1, fun2;但在这种情况下不是 aClass 复制构造函数(如果它没有在任何地方定义)。
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:
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:
友元类/函数可以访问类的所有私有/受保护/公共成员,友元类/函数位于哪个访问部分没有任何区别。
建议将友元类/函数放在公共部分,因为友元是类接口的一部分。
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.