友元类和访问器部分的定义

发布于 2024-10-31 04:54:13 字数 208 浏览 1 评论 0原文

将类定义为友元类时,定义放置在哪个访问器部分是否重要?如果是,是否会更改友元可以访问的成员?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

想你只要分分秒秒 2024-11-07 04:54:13

访问说明符不适用于友元函数/类
您可以在任何访问说明符下声明 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.

旧时浪漫 2024-11-07 04:54:13

一旦您将友元类/函数放置在给定类(例如“aclass”)任何地方中。它将有权访问该类的所有已定义成员(无论公共/私有/受保护);例如:

class aClass
{
public: int pub;  void fun1() {}
protected: int pro; void fun2() {}
private: int pri;  aClass(const aClass& o);  
  friend void outsider ();  
};

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:

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).

小巷里的女流氓 2024-11-07 04:54:13

按照惯例,友元函数不会放置在任何访问器中,因为根据定义它们不是类的一部分。你可能会做这样的事情:

class Elephants
{
 //friend void notAMemberFuncion(argument 123);

public:
// member functions;

protected:
// data members;
};

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;
};
愛放△進行李 2024-11-07 04:54:13

友元类/函数可以访问类的所有私有/受保护/公共成员,友元类/函数位于哪个访问部分没有任何区别。
建议将友元类/函数放在公共部分,因为友元是类接口的一部分。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文