通过包含文件在班级之间共享好友 我有一些旧的C++代码,其中朋友类都在一个空的包含文件中声明为类之外。然后在不同的类之间共享include文件,如下所示

通过包含文件在班级之间共享好友 我有一些旧的C++代码,其中朋友类都在一个空的包含文件中声明为类之外。然后在不同的类之间共享include文件,如下所示,c++,friend,C++,Friend,包括朋友 #pragma once friend class Friend1;// Error E0239 friend class Friend2;// Error E0239 朋友们 #pragma once class Friend1 { public: Friend1() {}; private: int pF1{0}; }; class Friend2 { public: Friend2() {}; private: int pF2{0}; };

包括朋友

#pragma once
friend class Friend1;// Error E0239
friend class Friend2;// Error E0239
朋友们

#pragma once
class Friend1
{
public:
    Friend1() {};
private:
    int pF1{0};
};

class Friend2
{
public:
    Friend2() {};
private:
    int pF2{0};
};

#pragma once
#include "Friends.h"
class Class1
{
#include "IncludeFriends.h"
public:
    Class1() {};
    int getFriendInt(Friend1& f1) { return f1.pF1; };
};

class Class2
{
#include "IncludeFriends.h"
public:
    Class2() {};
    int getFriendInt(Friend2& f2) { return f2.pF2; };
};
我得到以下错误:

1>------ Build started: Project: friendsTest, Configuration: Debug Win32 ------
1>classes.cpp
1>D:\friendsTest\classes.h(8,43): error C2248: 'Friend1::pF1': cannot access private member declared in class 'Friend1'
1>D:\friendsTest\Friends.h(7): message : see declaration of 'Friend1::pF1'
1>D:\friendsTest\Friends.h(2): message : see declaration of 'Friend1'
1>D:\friendsTest\classes.h(16,43): error C2248: 'Friend2::pF2': cannot access private member declared in class 'Friend2'
1>D:\friendsTest\Friends.h(15): message : see declaration of 'Friend2::pF2'
1>D:\friendsTest\friendsTest\Friends.h(10): message : see declaration of 'Friend2'
1>friendsTest.cpp
1>Generating Code...
1>Done building project "friendsTest.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我的编辑还对includepiles.h文件提出了额外的投诉。它声明:E0239类声明外的说明符无效

以此类推为n个数量的类和朋友类。 这在C++中不再被允许。我尝试将友元类封装在另一个类中,该类本身在所有类定义中声明为友元,但我了解到这不会起作用,因为友元类没有继承这类东西,对吗?我想知道是否有解决办法。我真的不想为每个类写所有的朋友,因为那样会使我的代码可读性降低。提前谢谢


编辑:因为有人评论说这里采用的一般方法不是最明智的,也许一种替代方法比必须解决实际问题要好。

遵循@n的建议代词m。我将
#include“IncludeFriends.h”
语句移动到Friend1和Friend2类定义中。但是请注意,这是一种非常矛盾的行为,我的编辑器仍然突出显示E0239错误,并将其显示在错误窗口中。不过,该项目确实成功编译。

预处理器只是一个剪切/粘贴自动化工具

您应该能够告诉编译器在预处理阶段后停止,或者将预处理文件写入磁盘(
g++-E
),在文本编辑器中打开预处理源代码,您将看到编译的确切内容。我相信你会马上发现问题的

这是唯一正确的做法-拥有你的构建,否则它将拥有你


也应该从<代码> <包涵朋友>中删除<代码> > > > >,虽然这不是你的问题的唯一原因。

什么让你认为C++中不允许这样做?你是说“[t]他的C++不再被允许”是什么意思?
#include
指令基本上是在指令点插入包含文件的原始内容。除非你在
friend.h
文件中有一些无效的代码,否则一切都很好(尽管可能不是我推荐的)。你如何编译它?您是否在其他地方也包括
friend.h
?你发布的代码看起来不错也许这是一个
#pragma once
问题?这将抑制单个翻译单元中的多个包含。如果将其从
IncludeFriends.h
中删除,会发生什么情况?如果能看到
friendsTest.cpp
,那也很好。友谊的作用正好相反。如果你让某人成为你的朋友,你就让他们接触你的私人部分。E023 9不是微软C++编译器产生的编译器错误,它必须是其他工具。如果您对此感到担忧,请另提一个问题。我建议您不要将您的好友声明放在头文件中。它容易混淆和出错。把它们直接放在需要它们的课堂上。