【问题标题】:Not able to access private member through friend function无法通过好友功能访问私人会员
【发布时间】:2017-03-18 13:52:48
【问题描述】:
#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:在成员函数“void R::convert(S)”中:prog.cpp:26:14: 错误:“int S::side”在此上下文中是私有的 宽度 = a.side; ^~~~ prog.cpp:16:8: 注意:这里声明为私有 整数边; ^~~~ prog.cpp:27:15: error: ‘int S::side’ 在这个上下文中是私有的 高度 = a.side; // 将 Square 解释为矩形 ^~~~ prog.cpp:16:8: 注意:这里声明为私有 整数边; ^~~~

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

【问题讨论】:

  • 朋友在 S 级而不是 R ...

标签: c++ friend


【解决方案1】:

class S 你应该有friend R;

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

【讨论】:

  • 感谢您的解决方案:)
【解决方案2】:

对于初学者,名称S 在首次用于声明之前未声明

void convert ( S a);  

其次,您必须指定函数 convert 是类 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);
              ^^^ 
};

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 2021-01-02
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多