1

我正在尝试创建一个非成员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& );
};

并且卡文件不起作用。

4

1 回答 1

2

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

#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&);
};
于 2013-03-05T20:03:14.913 回答