[英]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 上有很多问题与我的问题类似,但似乎都不是我需要的。
private
to protected
, but that didn't work, it just changed the error to say it can't access the protected member.private
切换到protected
,但这不起作用,它只是将错误更改为无法访问受保护的成员。#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.