【发布时间】:2021-06-29 10:47:35
【问题描述】:
美好的一天! 我目前正在尝试创建一个需要我创建两个 ADT 的数据库。其中一个有一个私人 本例中创建的 structlinkedlist
问题是我似乎无法在另一个类的函数中访问或至少打印出我的结构中的值
这是我从原始代码中导出的示例代码
#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 ,但我对如何做到这一点一无所知。如果有解决方案,我将不胜感激。
【问题讨论】:
-
您是否遇到编译错误?这是什么?
-
崩溃是因为
CPtr == NULL这里:cout << "Class B Integration: " << CPtr->var1 << endl;a和b是不同的对象,所以a.CNode();不会改变b中的变量。也许你想要b.c.CNode();?
标签: c++ class struct linked-list