gpt4 book ai didi

C++ 类 - 我的程序有什么问题?

转载 作者:行者123 更新时间:2023-11-27 23:23:42 24 4
gpt4 key购买 nike

Insert 是一种将项目附加到我的链表末尾的方法。

不知道如何为 Node 为 null 的情况编写代码,我只想添加它。

struct Node{
int data;
Node *next;

Node(int data):data(data),next(NULL){}

void insert(int data){
if (this==NULL){
this=new Node(data); // compiler is complaining here.
// how would I go about setting the value of this (which is presently NULL) to a new Node?
}
}
}

最佳答案

您不能为 this 指针赋值,这是一个特殊的关键字,应该始终指向有效的内存块。通过查看您的用法,您的意思是:

void insert(int data){
if (!next){
next = new Node(data);

}

关于C++ 类 - 我的程序有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com