如何通过不同的指针使用类的对象访问结构?(链表)(C++)

How do I access a structure using an object of a class through a different pointer?(LINKED LISTS)(C++)

本文关键字:结构 访问 C++ 对象 链表 何通过 指针      更新时间:2023-10-16

当我试图使用指向同一内存块的指针调用struct的成员时,我的程序崩溃。请原谅我最近才开始学习c++的糟糕代码(大约两个月了(。

#include "iostream"
using namespace std;
struct node 
{
int data;
node *next;
};
class trial
{
node *hello;
public:
trial()
{
hello=new node;
hello->data=0;
hello->next=NULL;
}
friend void access(trial);
void get();
};
void access(trial t1)
{
node *temp;
temp=t1.hello;
//My program stops working after I write the following line of code:
cout<<temp->data;
}
int main()
{
trial t1;
access(t1);
}

access()中,通过值传入t1参数,这意味着编译器将对输入对象进行复制。但是trial类不支持正确的复制语义(请参阅3/5/0规则(,因此t1参数没有正确初始化。

您应该通过引用传递t1参数,以避免复制:

void access(trial &t1)

最好通过const参考,因为access()不修改t1:

void access(const trial &t1)