通过函数访问另一个类中的私有struct LinkedList;

问题描述 投票:0回答:1

美好的一天! 我目前正在尝试创建一个数据库,需要我创建两个 ADT。其中一个拥有 私人 本例中创建的 struct linkedlist

问题是我似乎无法访问或至少打印出另一个类的函数中的结构内的值

这是我从原始代码中衍生出来的示例代码

#include <iostream> using namespace std; class A; class B; class A{ private: struct Node{ int var1; struct Node *next; }; Node *head = NULL; int var1 = 10; friend class B; public: void CNode(); }; void A::CNode(){ Node *CPtr, *NewNode; NewNode = new Node; NewNode -> var1 = var1; NewNode -> next = NULL; if(!head){ head = NewNode; } else{ CPtr = head; while(CPtr->next){ CPtr = CPtr->next; } CPtr->next = NewNode; } CPtr = head; while(CPtr){ cout << "Class A: " << CPtr -> var1 << endl <<endl; cout << CPtr -> next; break; } } class B{ A c; public: void Display(); }; void B::Display(){ //Problem lies here I think A::Node *CPtr; CPtr = c.head; cout << "Class B Integration: " << CPtr -> var1 << endl; } int main() { A a; B b; a.CNode(); b.Display(); }
问题出在

Display()。正如您所看到的,我正在尝试在另一个类中访问我的私有结构 LinkedList,但我对如何做到这一点没有任何线索或经验。如果有解决方案,我将不胜感激。

c++ class struct linked-list
1个回答
1
投票
首先,B 类中的属性

c

 是私有的。 B级没有地方可以体现这个价值。所以我添加了一个构造函数,它引用 A 的实例。

你做错了什么:

c

总是有一个空指针。现在介绍一下原始引用和指针。请务必检查
nullptr
。否则,您将得到未定义的行为,例如
没有显示

class B { A& c; public: B(A& c_) : c(c_){}; void Display(); }; void B::Display() { //Problem lies here I think A::Node *CPtr; CPtr = c.head; if (CPtr != nullptr) { cout << "Class B Integration: " << CPtr->var1 << endl; } else { cout << "Class B's A attribute is null" << endl; } } int main() { A a; B b(a); a.CNode(); b.Display(); }
    
© www.soinside.com 2019 - 2024. All rights reserved.