如何在多个类中使用友元函数

How to use friend function in multiple classes

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

我正在尝试创建一个非成员operator<<。但是,我希望两个类都可以访问该操作符。操作符是

void operator<< (ClassA & a, ClassB & b)

在两个类的公共部分,我说:

friend void operator<< (ClassA & a, ClassB & b);

然而,操作符可以访问CLass B中的私有成员变量,而不能访问Class A中的私有成员变量。

为什么?

实际代码:在cpp文件中:

void operator<< (Hand& h, Deck& d){
    h.hand.push_back(d.card[0]);
    sort(h.hand.begin(),h.hand.end());
    d.card.erase(d.card.begin());
}

头文件:

class Deck {
private:
    vector<Card> card;
public:
    friend void operator<< (Hand& , Deck& );
};
class Hand {
private:
    vector<Card> hand;
public:
    friend void operator<< (Hand& , Deck& );
};

卡片文件不工作

更新为编辑后的问题:以下代码对我来说编译没有问题:

#include <vector>
#include <algorithm>
typedef int Card;
class Hand; // NOTE forward declaration
class Deck {
private:
    std::vector<Card> card;
public:
    friend void operator<< (Hand& , Deck&);
};
class Hand {
private:
    std::vector<Card> hand;
public:
    friend void operator<< (Hand& , Deck&);
};
void operator<< (Hand& h, Deck& d) {
    h.hand.push_back(d.card[0]);
    std::sort(h.hand.begin(),h.hand.end());
    d.card.erase(d.card.begin());
}
int main()
{
}

您是否忘记在头文件中转发声明Hand ?


您可能会感到困惑,因为可以在类的一个声明中定义静态友元函数的主体。然而,友元声明始终只是一个声明。因此,实际上

struct A;
struct B;
struct A
{
    friend bool operator<<(A const&, B const&);
};
struct B
{
    friend bool operator<<(A const&, B const&);
};
bool operator<<(A const&, B const&)
{
    // access to both A and B
    return false;
}

等价于

struct A;
struct B;
struct A
{
    friend bool operator<<(A const&, B const&)
    {
        // access to both A and B
        return false;
    }
};
struct B
{
    friend bool operator<<(A const&, B const&);
};