gpt4 book ai didi

c++ - 运算符 -> 在 C++ 中无法按预期工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:20 26 4
gpt4 key购买 nike

我在c++中练习单链表(练习如何找到循环列表的起始节点),但是发现operator ->的使用非常困惑。我正在使用 Visual Studio 2010 C++ Express

这完美地工作:head->append(2)->append(3)->append(4)->append(5)

但这不起作用(创建循环链表):head->append(2)->append(3)->append(4)->append(5)->append( head->下一个)

当我跳入此方法并进行调试时,head->next 似乎未正确传递到该方法中。

但这行得通:

  1. Node* tail=head->append(2)->append(3)->append(4)->append(5);
    tail->append(head->next);
  2. 或者我把这两个方法中的return c->next改成return head之后,head->append(2)->append(3) ->append(4)->append(5)->append(head->next) 也可以。

我在这里错过了什么?谢谢!

我的代码详情如下:

void main(){
Node* head=new Node(1);
Node* tail=head->append(2)->append(3)->append(4)->append(5)->append(head->next);
cin.get();
}

class Node{
public:
Node* next;
int data;
bool marked;

Node(int d){
data=d;
marked=false;
next=NULL;
}

Node* append(int d){
Node* c=this;
while(c->next!=NULL){
c=c->next;
}
c->next=new Node(d);
return c->next;
}

Node* append(Node* n){
Node* c=this;
while(c->next!=NULL){
c=c->next;
}
c->next=n;
return c->next;
}
};

最佳答案

您遇到未定义的行为

问题是您期望 head->next 在特定时间被评估(就在调用最后一个 append() 之前)。但这并不能保证.

关于c++ - 运算符 -> 在 C++ 中无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8717523/

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