简体   繁体   English

(朋友类的)成员“Node::next”不可访问

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

I am building my own LinkedList , because I need a special Node that holds more data.我正在构建自己的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. 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.

Node.h节点.h

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

LinkedList.h链表.h

#include "Node.h"

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

LinkedList.cpp链表.cpp

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

1 This is where I get the error. 1这是我得到错误的地方。 It says that the this->root->next is inaccessible, but I have it as a friend class to my LinkedList and so private variables should be accessible to it.它说this->root->next是不可访问的,但我将它作为我的LinkedList的朋友 class ,因此它应该可以访问私有变量。

There are quite a few questions here on Stack Overflow that talk about something similar to my question, but none of them seem to be what I need. Stack Overflow 上有很多问题与我的问题类似,但似乎都不是我需要的。

  • One answer was saying to switch from private to protected , but that didn't work, it just changed the error to say it can't access the protected member.一个答案是说从private切换到protected ,但这不起作用,它只是将错误更改为无法访问受保护的成员。
  • Another answer was saying that they had a misspelling in there friend declaration.另一个答案是说他们在朋友声明中有拼写错误。 I checked mine, and it is spelled correctly.我检查了我的,它拼写正确。
  • Another was saying to make sure that the classes are declared in the correct order, but since I have them in different files, and #include the file where I create the class that is declared as a friend.另一个人说要确保以正确的顺序声明这些类,但是因为我将它们放在不同的文件中,并且#include我创建声明为朋友的 class 的文件。

There were quite a few more that I looked at, but all were similar to the above mentioned and didn't help me solve my problem.我看了很多,但都与上面提到的相似,并没有帮助我解决我的问题。

What am I missing/not understanding?我错过了什么/不理解什么? Nothing I've tried has worked, and I would really appreciate any help.我尝试过的任何方法都没有奏效,我非常感谢任何帮助。

A friend declaration grants access of the specified class to the private members of the declarating class. friend元声明将指定 class 的访问权限授予声明 class 的私有成员。 So, you are granting Node access to LinkedList 's private members, not the other way around like you want.因此,您授予Node访问LinkedList的私有成员的权限,而不是您想要的相反方式。 So, you need to move the friend statement into Node instead:因此,您需要将friend语句移动到Node中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM