Error: ‘int XYZ::data’ is private within this context

Error: ‘int XYZ::data’ is private within this context

我对以下 C++ 代码片段有一个疑问:

 #include <iostream>

 using namespace std;

 class ABC;

 class XYZ
 {
 int data;
 public:

         void setvalue(int value)
         {
         data=value;
         } 
         friend void add(ABC,XYZ);
 };

 class ABC
 {
 int data;
 public:

         void setvalue(int value)
         {
         data=value;
         }
         friend void add(ABC,XYZ);
 };

 void add(XYZ obj1, ABC obj2)
 {
      cout << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data;
      cout << "\n";
 }


 int main()
 {

 XYZ X;
 ABC A;

 X.setvalue(5);
 A.setvalue(50);
 add(X,A);

 return 0;
 }

特别是,当我编译时,g++ 抱怨以下日志:

g++ -Wall -Wextra -Werror friend_function_add_data.cpp -o friend_function_add_data.o
friend_function_add_data.cpp: In function ‘void add(XYZ, ABC)’:
friend_function_add_data.cpp:33:86: error: ‘int XYZ::data’ is private within this context
  33 | ut << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data;
     |                                                                                    ^~~~

friend_function_add_data.cpp:9:5: note: declared private here
   9 | int data;
     |     ^~~~
friend_function_add_data.cpp:33:98: error: ‘int ABC::data’ is private within this context
  33 |  data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data;
     |                                                                                   ^~~~

friend_function_add_data.cpp:21:5: note: declared private here
  21 | int data;
     |

因为它抱怨 data 声明为 private,我通过将 data 放在 public 语句之后将声明更改为 public每个 class ABCXYZ .

这样g++编译没有问题

我想知道的是:对于这个例子,这是处理这个问题的唯一正确方法吗?你认为这只是作者自己的错误吗?

这段代码摘自Balagurusamy的《OOP programming with C++》(第8版,第124页)

编辑:感谢 Anoop 仔细检查!我意识到我颠倒了每个 class ABC 和 XYZ,w.r.t 的输入参数。到采用 XYZ obj1 和 ABC obj2 的外部添加函数。所以书上写对了

问题是在定义函数add时,obj1obj2两个参数的顺序是相反的好友声明.

中的内容

所以要解决这个问题,请确保参数在定义和友元声明中的顺序匹配,如下所示:

class XYZ
{
public:
     //other code here
     friend void add(ABC,XYZ);
};
class ABC
{
public:

     //other code here
     friend void add(ABC,XYZ);
};
//ORDER OF PARAMETERS CHANGED TO MATCH WITH THE FRIEND DECLARATION
void add(ABC obj1, XYZ obj2)
{
  cout << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data + obj2.data;
  cout << "\n";
}
int main()
{

    XYZ X;
    ABC A;
    
    X.setvalue(5);
    A.setvalue(50);
    add(A,X); //ORDER OF ARGUMENTS CHANGED
}

Demo