【问题标题】:Member function of a class as friend to another class一个类的成员函数作为另一个类的朋友
【发布时间】:2015-08-23 19:28:23
【问题描述】:

在这段代码中,我做了A类的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);
}

【问题讨论】:

标签: c++ c++11 visual-c++ forward-declaration friend-function


【解决方案1】:

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

【讨论】:

  • 调整了答案来纠正自己,这一点没有必要
【解决方案2】:

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

【讨论】:

  • 正要回答这个问题:)
【解决方案3】:

你不能使用:

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

没有B的完整定义。

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

【讨论】:

  • 请告诉我该怎么做。
  • 你可以friend class B,如果你和整个班级的朋友都没有问题。
  • 我可以声明 void B:: max(A,B);在 B 类前向声明​​之后;
  • @ishanbansal,不,你不能那样做。
猜你喜欢
  • 2012-05-19
  • 2021-08-29
  • 2016-11-26
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多