无法通过好友功能访问私有成员

Not able to access private member through friend function

#include <iostream>
using namespace std;

class S;

class R {
        int width, height;
        public:
        int area ()   // Area of rectangle
   {return (width * height);}
    void convert (S a);  
};
class S {
   private:
   int side;
   public:
   S (int a) : side(a) {}
   friend void convert(S a);

};

void R::convert (S a) {    
   width = a.side;
   height = a.side;    // Interpreting Square as an rectangle
}
int main () {

   int x;

   cin >> x;
   R rect;
   S sqr (x);
   rect.convert(sqr);
   cout << rect.area();
   return 0;
}

我收到以下错误:

prog.cpp: In member function ‘void R::convert(S)’: prog.cpp:26:14: error: ‘int S::side’ is private within this context width = a.side; ^~~~ prog.cpp:16:8: note: declared private here int side; ^~~~ prog.cpp:27:15: error: ‘int S::side’ is private within this context height = a.side; // Interpreting Square as an rectangle ^~~~ prog.cpp:16:8: note: declared private here int side; ^~~~

我也试过将友元函数设为私有,但同样的错误。 请帮助

class S 你应该有 friend R;

friend void convert(S a); 没有意义,因为编译器甚至不知道 convert 属于 R 而不是 S。

对于初学者来说,名称 S 在首次用于声明之前未声明 [​​=15=]

void convert ( S a);  

其次,您必须指定函数 convert 是 class R 的成员函数。

尝试以下方法

class R {
        int width, height;
        public:
        int area ()   // Area of rectangle
   {return (width * height);}
    void convert ( class S a);  
                   ^^^^^^
};
class S {
   private:
   int side;
   public:
   S (int a) : side(a) {}
   friend void R::convert(S a);
              ^^^ 
};