c++ - 好友功能无法访问私有(private)成员

标签 c++ friend-function

在阅读C++ Primer时,我遇到了以下代码片段(我省略了我认为不相关的代码):

class Message {
  friend class Folder;

 public:
  // ...

 private:
  std::string contents;
  std::set<Folder*> folders;
  // ...
};

// ...
void swap(Message& lhs, Message& rhs) {
  using std::swap;
  for (auto f : lhs.folders) { f->remMsg(&lhs); }
  // class Folder is undefined by book
  // ...
}
// ...

C++ Primer给出了实现类文件夹的任务。所以我添加更多代码::

class Folder;   // my code

class Message {
  friend void swap(Message&, Message&);  // my code
  friend class Folder;

 public:
  // ...

 private:
  std::string contents;
  std::set<Folder*> folders;
  // ...
};

void swap(Message&, Message&);  // my code

// I added the whole class
class Folder {
  friend void swap(Folder&, Folder&);
  friend class Message;

 public:
  // ...

 private:
  // ...
  void addMsg(Message* m) { msgs.insert(m); }
  void remMsg(Message* m) { msgs.erase(m); }
};

void swap(Folder&, Folder&);    // my code

file.cpp

void swap(Message& lhs, Message& rhs) {
  using std::swap;
  for (auto f : lhs.folders) { f->remMsg(&lhs); }
  // In vs2019 
  // Error (active) E0265   function "Folder::remMsg" is inaccessible
  // ...
}

如您所见,我无法使用 Folder::remMsg() 方法。

然后我尝试弄清楚好友功能是如何工作的。

struct B;  // This is [line 1]

struct A {
  friend void swap(A&, A&);

 private:
  int n;
  std::vector<B*> Bs;
};

void swap(A& lhs, A& rhs) {
  for (auto f : lhs.Bs) { f->n; }
  // f->n is still inaccessible
  // If I delete line 1, the code can be compiled successfully
  // same with class Folder
  // ...
}

struct B {
  friend struct A;

 private:
  int n;
  A C;
};

我不明白为什么会发生这种情况。

(我声明 class Messageclass Folder 彼此为友元类,因为我希望对称 swap 使用复制交换)

最佳答案

void swap(Message& lhs, Message& rhs)Message 的 friend ,但您尝试访问 Folder 的私有(private)成员。您的最后一个代码有同样的问题:friend void swap(A&, A&);A 的 friend 但您尝试访问 B 的私有(private)成员。 friend不具有传递性。只是因为AB 的 friend 和swapA 的 friend 并不意味着swapB 的 friend .

如果你想要void swap(A&,A&)B 的私有(private)成员授予访问权限然后将其设为 B 的好友:

#include <vector>

struct B;

struct A {
  friend void swap(A&, A&);

 private:
  int n;
  std::vector<B*> Bs;
};

struct B {
  friend void swap(A&,A&);

 private:
  int n;
  A C;
};

void swap(A& lhs, A& rhs) {
  for (auto f : lhs.Bs) { f->n; }
                // ^^ access private member of A
                        //^^ access private member of B
}

关于c++ - 好友功能无法访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69282858/

相关文章:

c++ - 使用 Objective-C++ 从字节数组中读取特定字节并将它们转换为十六进制表示

c++ - 仅使用质数 2、3 和 5 生成序列,然后显示第 n 项 (C++)

c++ - 为什么我们在 C++ 中使用返回数据结构的函数?

c++ - 有没有办法为两个类声明共同的 friend 函数

c++ - ostream& 运算符中的类型转换 <<

c++ - 使用 Prim 算法的六角形迷宫

c++ - 错误 : cannot convert ‘int (^)(int)’ to ‘R (^)(T)’ in initialization

c++ - 友元函数的参数依赖查找

c++ - C++ 中的友元函数

c++ - 在C++中,如何从另一个类中添加静态函数