【问题标题】:friend with class but can't access private members有班级的朋友,但无法访问私人成员
【发布时间】:2023-04-06 08:46:01
【问题描述】:

Friend函数应该可以访问一个类的私有成员吧? 那么我在这里做错了什么?我已将我的 .h 文件包含在运算符中

#include <iostream>

using namespace std;
class fun
{
private:
    int a;
    int b;
    int c;


public:
    fun(int a, int b);
    void my_swap();
    int a_func();
    void print();

    friend ostream& operator<<(ostream& out, const fun& fun);
};

ostream& operator<<(ostream& out, fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}

【问题讨论】:

    标签: c++ friend


    【解决方案1】:

    在这里……

    ostream& operator<<(ostream& out, fun& fun)
    {
        out << "a= " << fun.a << ", b= " << fun.b << std::endl;
    
        return out;
    }
    

    你需要

    ostream& operator<<(ostream& out, const fun& fun)
    {
        out << "a= " << fun.a << ", b= " << fun.b << std::endl;
    
        return out;
    }
    

    (我已经被这个问题咬过很多次了;你的运算符重载的定义与声明不完全匹配,所以它被认为是一个不同的函数。)

    【讨论】:

    • fun&amp; 是否总是必须是 const
    • @peter 不,它不必是 const (尽管您的声明必须与您的定义相匹配)。但是,这样做是“最佳实践”。作为该函数的用户,您不会期望写入输出流会更改对象的状态。
    【解决方案2】:

    签名不匹配。你的非成员函数需要 fun& fun,声明的朋友需要 const fun& fun。

    【讨论】:

      【解决方案3】:

      您可以通过在类定义中编写友元函数定义来避免此类错误:

      class fun
      {
          //...
      
          friend ostream& operator<<(ostream& out, const fun& f)
          {
              out << "a= " << f.a << ", b= " << f.b << std::endl;
              return out;
          }
      };
      

      缺点是对operator&lt;&lt; 的每次调用都是内联的,这可能会导致代码膨胀。

      (另请注意,该参数不能称为fun,因为该名称已表示类型。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多