【问题标题】:How to execute friend class?如何执行朋友班?
【发布时间】:2019-09-17 17:04:02
【问题描述】:

我试图实现朋友类为另一个类的成员提供成员的价值。

我尝试创建class Friend 的对象并将其定义为Attempt 的参数,并将&Friend::fri 替换为object.fri(),但它也没有编译。

 class Friend {
  public:
    int val = 0;
int fri() {
    val = 456;
    return val;         
          }
friend class Partner;
 };

 class Partner {    
  public:
//(corrected) Friend Object;
int Attempt() {
    std::cout << "The value from the friend class: " << 
     &Friend::fri /*(corrected) Object.fri()*/<<"\n"; // '&' was requred by compiler to make pointer to 
                        //the member
    return 0;
      }
 };

我希望 Attempt 写入来自 fri() 的值。但是有 1,我不明白这个 1 是从哪里来的。

【问题讨论】:

    标签: c++ class friend


    【解决方案1】:

    friend 关键字只是让非成员函数可以访问另一个类的私有/受保护成员。除非您的方法是静态的,或者涉及继承,否则您仍然需要一个对象来调用该方法。举个例子:

    Friend f;
    int Attempt(){
        std::cout << "The value from the friend class: " << f.fri();
    }
    

    这将产生您所期望的输出。

    【讨论】:

    • 谢谢,确实返回了所需的值。
    • @Konstantin 很高兴它有帮助。如果它解决了您的问题,请随时将其标记为正确,以防其他人将来遇到此问题:)
    • 之前我更正了代码,后来有人写了不要这样做,现在我真的不知道问题解决后该怎么办)猜猜我在代码中是否会做注释最好的解决方案)
    猜你喜欢
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2016-02-27
    • 2011-03-23
    相关资源
    最近更新 更多