簡體   English   中英

(朋友類的)成員“Node::next”不可訪問

[英]member "Node::next" (of a friend class) is inaccessible

我正在構建自己的LinkedList ,因為我需要一個保存更多數據的特殊Node I specify that my Node class is a friend of the LinkedList class, but it doesn't seem to allow me to access the private variables in the Node class from the LinkedList class.

節點.h

class Node {
    private:
        Node* next;
    ...
};

鏈表.h

#include "Node.h"

class LinkedList {
    friend class Node;
    ...
};

鏈表.cpp

...
void LinkedList::insertFirst(Node* n) {
    Node* temp = this->root;
    this->root = n;
    this->root->next = temp; // 1
}
...

1這是我得到錯誤的地方。 它說this->root->next是不可訪問的,但我將它作為我的LinkedList的朋友 class ,因此它應該可以訪問私有變量。

Stack Overflow 上有很多問題與我的問題類似,但似乎都不是我需要的。

  • 一個答案是說從private切換到protected ,但這不起作用,它只是將錯誤更改為無法訪問受保護的成員。
  • 另一個答案是說他們在朋友聲明中有拼寫錯誤。 我檢查了我的,它拼寫正確。
  • 另一個人說要確保以正確的順序聲明這些類,但是因為我將它們放在不同的文件中,並且#include我創建聲明為朋友的 class 的文件。

我看了很多,但都與上面提到的相似,並沒有幫助我解決我的問題。

我錯過了什么/不理解什么? 我嘗試過的任何方法都沒有奏效,我非常感謝任何幫助。

friend元聲明將指定 class 的訪問權限授予聲明 class 的私有成員。 因此,您授予Node訪問LinkedList的私有成員的權限,而不是您想要的相反方式。 因此,您需要將friend語句移動到Node中:

class Node {
    friend class LinkedList;
    ...
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM