成员函数在C++中用作友元函数

Member functions as Friend functions in C++

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

我在运行以下代码以使用友元函数时收到错误。我的类XYZ1有一个友元函数,它是ABC1类的成员函数(findMax)。我的类声明如下

class XYZ1;
class ABC1
{
    int a;
    public :
    ABC1()
    {
        a =20;
    }
    void findMax(XYZ1 p)
    {
        if (p.x > a) cout<< "Max is "<<p.x;
        else cout <<"Max is "<<a;
    }
};
class XYZ1
{
    int x;
    public :
    XYZ1()
    {
        x =10;
    }
    friend void ABC1::findMax(XYZ1);
};
 main()
{
    XYZ1 p;
    ABC1 q;
    q.findMax(p);
}

错误:friend3.cpp:14:7: 错误:"p"的类型不完整friend3.cpp:4:7:错误:"结构 XYZ1"的前向声明

请帮忙

在定义类 XYZ1 之后定义 findMax 方法。

#include <iostream>
using namespace std;
class XYZ1;
class ABC1
{
    int a;
    public :
    ABC1()
    {
        a =20;
    }
    void findMax(XYZ1 p);
};
class XYZ1
{
    int x;
    public :
    XYZ1()
    {
        x =10;
    }
    friend void ABC1::findMax(XYZ1);
};
void ABC1::findMax(XYZ1 p)
    {
        if (p.x > a) cout<< "Max is "<<p.x;
        else cout <<"Max is "<<a;
    }
int main()
{
    XYZ1 p;
    ABC1 q;
    q.findMax(p);
    return 0;
}

您必须具有完整的class XYZ1声明,编译器才能编译使用它的代码。

因此,将void findMax(XYZ1 p)的实现移至class XYZ1声明下方:

class ABC1
{
    ...
    void findMax(XYZ1 p);
};
class XYZ1
{
    ...
    friend void ABC1::findMax(XYZ1 p);
};
void ABC1::findMax(XYZ1 p)
{
    ...
}