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

C++ 如何在多个类中使用友元函数,c++,function,friend,C++,Function,Friend,我正在尝试创建一个非成员的操作符更新已编辑的问题:以下代码编译对我来说没有问题: #include <vector> #include <algorithm> typedef int Card; class Hand; // NOTE forward declaration class Deck { private: std::vector<Card> card; public: friend void operator<<

我正在尝试创建一个非成员的
操作符更新已编辑的问题:以下代码编译对我来说没有问题:

#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()
{
}
#包括
#包括
输入卡;
班长;//附注:远期申报
甲板{
私人:
向量卡;
公众:

friend void运算符只要在两个类中都放置friend声明,就可以了。这些声明或运算符的定义可能有问题。您应该显示真实代码您确定要@milleniumbug“当然”?这是胡说八道。这不是一个流插入运算符。您仍然可以实现该运算符的流插入重载。没有问题,不会导致任何特殊问题。也就是说,我可能更希望它是一个非运算符函数。@user1933“卡文件不起作用”-你包括头文件了吗?有什么问题吗?有错误消息吗?是什么问题?@sehe,直到有人把它用作子表达式,而gotchas是关于
a的含义,它与问题有什么关系?@Slava注意到问题是经过编辑的,当它说的时候我回答了。我也刚刚更新了我的答案,我看到了thanks,我也考虑过转发声明,但是如果没有类的转发声明,那么friend函数声明会编译吗?@sehe Yep,我一开始没有声明类。我们的老师从来没有教过我们这个。谢谢!
friend void operator<< (ClassA & a, ClassB & b);
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()
{
}
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&);
};