2

フレンド関数を使用して<<演算子をオーバーロードしようとしていますが、何らかの理由でプライベートメンバー変数が表示されません。なぜこれが起こっているのかという考えは非常に役に立ちます。

これがヘッダーファイルです

    class Set
    {
private:
    struct Node
    {
        int val;
        Node* link;
    };

    Node *cons(int x, Node *p);
    Node *list;


public:
    Set() {list = NULL;}
    bool isEmpty() const;
    int size() const;
    bool member (int x) const;
    bool insert (int x);
    bool remove (int x);
    void print() const;
    const Set operator+(const Set &otherSet)const;
    const Set operator*(const Set &otherSet)const;
    Node* getSet()const{return list;}
    void setList(Node *list);
    friend ostream& operator <<(ostream& outputStream, const Set &set);
    };

これが関数の定義です。

    ostream& operator <<(ostream& outputStream, const Set &set)
    {
              Node *p;
              p = list;
              outputStream << '{';
              while(p->link != NULL)
              {
                outputStream << p->val;
                p = p->link;
              }
              outputStream << '}';
              return outputStream;
    }
4

2 に答える 2

5

問題は のアクセシビリティではNodeなく、そのスコープにあります。修飾されていない型名は、友情によってスコープ内にならないため、Set::Node代わりに使用する必要があります。

list変数についても同様ですset.list

これら 2 つの変更を行うと、コードは ideone で正常にコンパイルされます

于 2012-11-22T03:52:23.890 に答える
1

コードの単純化した表現は次のとおりです。

class A
{
    struct MY
    {
        int a;
    };
    friend void doSomething(A);
};

void doSomething(A)
{
    MY *b;

}
int main()
{
    return 0;
}

問題は次のとおりです。

MY *b;

MYクラス 内で宣言されているため、関数は の型を理解できませんA。したがって、エラー:

In function 'void doSomething(A)':
Line 12: error: 'MY' was not declared in this scope
compilation terminated due to -Wfatal-errors.

My内部を検索するように関数に指示するには、構造の完全修飾名Aを使用する必要があります。

A::MY *b;

これを行うと、関数はどこを探すべきかを正確に認識しMY、それを見つけることができます。
作業オンライン サンプル.

于 2012-11-22T03:56:41.750 に答える