操作员->;不';t在C+中按预期工作+; 我在C++中练习单链表(练习如何找到循环链表的起始节点),但发现使用运算符> 非常混淆。我使用Visual Studio 2010 C++ Express < /P>

操作员->;不';t在C+中按预期工作+; 我在C++中练习单链表(练习如何找到循环链表的起始节点),但发现使用运算符> 非常混淆。我使用Visual Studio 2010 C++ Express < /P>,c++,operator-keyword,C++,Operator Keyword,这非常有效:head->append(2)->append(3)->append(4)->append(5) 但这不起作用(创建循环链表):head->append(2)->append(3)->append(4)->append(5)->append(head->next) 当我跳入这个方法并调试时,似乎head->next没有正确地传递到该方法中 但这是可行的: Node*tail=head->append(2)->append(3)->append(4)->append(5); 尾部->附

这非常有效:
head->append(2)->append(3)->append(4)->append(5)

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

当我跳入这个方法并调试时,似乎
head->next
没有正确地传递到该方法中

但这是可行的:

  • Node*tail=head->append(2)->append(3)->append(4)->append(5);
    尾部->附加(头部->下一步)
  • 或者在这两种方法中将
    returnc->next
    更改为
    returnhead
    后,
    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;
        }
    };
    

    当您传递
    头->下一步
    时,在使用
    头->附加
    更改它之前,先传递它。恐怕你把书写顺序和执行顺序混淆了


    在本例中,您正在更改值并在同一执行语句中读取它,这是未定义的行为。

    您正在经历未定义的行为


    问题是,您希望在特定时间(就在调用最后一个
    append()
    之前)对
    head->next
    进行求值,但这并不能保证。

    head->next
    首先求值。编译器可以自由地进行此操作;请参阅。

    head->next为NULL(不指向任何内容)在这个语句被评估的时候,

    是间接链接的新记录吗?@ MyStudio-我想我在一个项目中使用了一个较长的链,但是我已经失去了它的跟踪。所以它不是在C++标准中定义的,每个编译器都可以用自己的方式来解释它。这是正确的。当评估顺序对你很重要时。(如这里所示),将这些调用分开。可能不是,但很可能。我们必须检查编译器输出的内容才能确定,但最有可能的是它在整个语句的求值开始时使用head->next的值。构造函数将next设置为NULL。