c++ - 好友功能可访问性问题

标签 c++ friend

我正在尝试为另一个类创建友元函数,但我当前的布局导致访问问题和 header 包含问题。

在我的项目中,我有两个文件:A 类和 B 类。为了简洁起见,所有内容都内联在头文件中,因为它仍然演示了我的问题。

#ifndef CLASSA
#define CLASSA

#include "ClassB.h"

class A {
   private:
      int x;
   public:
      A(int x) {
          this->x = x;
      }
      friend void testFriend(A in);
};

#endif

#pragma once
#ifndef CLASSB
#define CLASSB
#include <cstdio>
#include "ClassA.h"

class B {
public:
   void testFriend(A in) {
       printf("%d", in.x);
   }
};
#endif

但是,对于这种设置,Visual Studio 认为类 A 的私有(private)成员元素是不可访问的,尽管它是一个成员函数。此外,它们相互包含,最终会导致错误。但是,当这两个类位于同一个头文件中时,此设置工作正常。我怎样才能实现这样的设置,其中一个类有一个成员函数需要与另一个类成为 friend ,同时让这两个类位于单独的头文件中。

最佳答案

friend void testFriend(A in);B::testFriend 无关。

你可以让全类同学成为 friend :

class A {
   private:
      int x;
   public:
      A(int x) : x(x) {}
      friend class B;
};

class B {
public:
   void testFriend(A a) { std::cout << a.x; }
};

关于c++ - 好友功能可访问性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673640/

相关文章:

c++ - 我在这个套接字中错过了什么? (Windows 套接字)

c++ - g++ 4.5 找不到友元函数

c++ - 私有(private)枚举访问无法从嵌套类的友元函数编译

C++ 如何通过回调方法访问成员变量

c++ - 访问私有(private)类或 protected 类的构造函数?

c++ - 'struct Node' 的无效使用/转发声明

c++ - 如何使 WSAAsyncSelect 在应用程序控制台中启动?

c++ - 迭代 C++ list<derived> 作为基类

c++ - gets() 被认为是 C 函数还是 C++ 函数?

c++ - Pyclewn 中的标准输入/输出(vim 的 GDB 前端)