类的成员函数作为另一个类的友元

Member function of a class as friend to another class

本文关键字:另一个 友元 函数 成员      更新时间:2023-10-16

在这段代码中,我将类B的max函数设置为类a的朋友,我还对类B进行了前向声明,但是它给出了错误

#include<iostream>
using namespace std;
class B;
class A
{
   int a;
   public:
   void get()
   {
      cin>>a;
   }
   friend void B :: max(A , B);
};
class B
{
   int b;
   public:
   void get()
   {
      cin>>b;
   }
   void max(A x, B y)
   {
      if (x.a > y.b)
         cout<< " x is greater";
      else cout<<"y is greater";
   }
};
int main()
{
   A x;
   B y,c;
   x.get();
   y.get();
   c.max(x,y);
}

B在声明B::max为友元方法时是不完整的。因此,编译器不知道是否存在这样的方法。

这意味着您需要

  1. 重新排序类,使A知道B有方法B::max
  2. 在类定义之外实现方法B::max,当两个类都完成时,因为您访问内部变量。

通过const引用传递参数也是一个好主意。使用const来强调您没有修改它们。通过引用传递以避免不必要的复制。

因此,考虑到这一点:

class A;
class B{
    int b;
public: 
    void get(){
        cin>>b;
    }
    void max(const A& x, const B& y);
};
class A{
    int a;
public:
    void get(){
        cin>>a;
    }
    friend void B :: max(const A& , const B&);
};
void B::max(const A& x, const B& y) {
    if (x.a > y.b)
       cout<< " x is greater";
    else
        cout<<"y is greater";
}

As R Sahu已经回答:

不能使用:

friend void B :: max(A , B);
没有b的完整定义的

这是你实现目标的方法:

#include<iostream>
using namespace std;
class A;
class B{
    int b = 2;
public: 
    void max(A x, B y);
};
class A{
    int a = 1;
public:
    friend void B :: max(A , B);
};
void B::max(A x, B y){
    if (x.a > y.b)
        cout<< " x is greater";
    else 
        cout<<"y is greater";
}
int main(){
A x;
B y,c;
c.max(x,y);
}

不能使用:

friend void B :: max(A , B);

没有B的完整定义。

您需要重新考虑您的策略,以便您可以在不使用friend声明或将B的定义移动到A定义之前的情况下实现该功能。

相关文章: