如何通过不同的指针使用 class 的对象访问结构?(链接列表)(C++)
How do I access a structure using an object of a class through a different pointer?(LINKED LISTS)(C++)
当我尝试使用指向同一内存块的指针调用结构成员时,我的程序崩溃了。请原谅我最近才接触到 c++ 的糟糕代码(已经大约 2 个月了)。
#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
class 不支持正确的复制语义(请参阅 Rule of 3/5/0),因此 t1
参数未正确初始化。
您应该通过引用传递t1
参数以避免复制:
void access(trial &t1)
最好通过 const
引用代替,因为 access()
不会修改 t1
:
void access(const trial &t1)
当我尝试使用指向同一内存块的指针调用结构成员时,我的程序崩溃了。请原谅我最近才接触到 c++ 的糟糕代码(已经大约 2 个月了)。
#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
class 不支持正确的复制语义(请参阅 Rule of 3/5/0),因此 t1
参数未正确初始化。
您应该通过引用传递t1
参数以避免复制:
void access(trial &t1)
最好通过 const
引用代替,因为 access()
不会修改 t1
:
void access(const trial &t1)