简体   繁体   English

一个班级的成员功能成为另一个班级的朋友

[英]Member function of a class as friend to another class

In this code , i have made max function of class B friend of class AI have also done forward declaration of class B.But it is giving error. 在这段代码中,我使AI类的B类max函数成为朋友,也对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);
}

As R Sahu already answered: 正如R Sahu已经回答的那样:

You cannot use: 您不能使用:

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

without the complete definition of B. 没有B的完整定义。

This is how you can achieve your goal: 这是实现目标的方法:

#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);
}

B is incomplete at the point where you declare B::max as a friend method. 在您将B::max声明为朋友方法时, B是不完整的。 Thus, compiler does not know if there is such a method. 因此,编译器不知道是否存在这种方法。

This means that you need to 这意味着您需要

  1. reorder classes, so that A knows B has a method B::max and 重新排序类,以便A知道B具有方法B::max
  2. Implement the method B::max outside of the class definition, when both classes are complete, because you access internal variables. 当两个类都完成后,在类定义之外实现方法B::max ,因为您可以访问内部变量。

It is also a good idea to pass your arguments by const reference. 通过const引用传递参数也是一个好主意。 Use const to emphasise that you are not modifying them. 使用const强调您没有修改它们。 Pass by reference to avoid unnecessary copying. 通过引用传递以避免不必要的复制。

So, with this in mind: 因此,请记住以下几点:

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";
}

You cannot use: 您不能使用:

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

without the complete definition of B . 没有B的完整定义。

You'll need to rethink your strategy so that you can implement the functionality without using the friend declaration or move the definition of B ahead of the definition of A . 你需要重新考虑你的战略,这样就可以在不使用实现该功能friend声明或移动的定义B提前定义的A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM