1

非メンバーを作成しようとしていますoperator<<。ただし、2 つのクラスからオペレーターにアクセスできるようにしたいと考えています。オペレーターは

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

2 つのクラスの公開部分では、次のように言います。

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 を宣言するのを忘れましたか?


クラスの宣言の 1 つの内部で静的フレンド関数の本体を定義できるため、混乱する可能性があります。

それでも、フレンド宣言は常に単なる宣言です。だから、実際には

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 に答える