繁体   English   中英

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

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

在这段代码中,我使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);
}

正如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);
}

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

这意味着您需要

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

您不能使用:

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

没有B的完整定义。

你需要重新考虑你的战略,这样就可以在不使用实现该功能friend声明或移动的定义B提前定义的A

暂无
暂无

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

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