为什么C ++的行为不同于debuging? [英] Why C++ act differently from debuging?

查看:90
本文介绍了为什么C ++的行为不同于debuging?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c ++中实现了LinkedList。



我原以为:



I was implemeting LinkedList in c++.

I was expecting :

List is not empty!!
4	





结果是:





But result was :

List is not empty!!
5	





有趣的是当我调试时所以'跳过'并且重新开始,我得到了预期的结果。有没有人告诉我,我错过了什么?









and Funny how that when I debug and so 'Step over' and over again, I got the expected result. Is there anyone who tells me that I'm missing something?



#include <iostream>
using namespace std;

struct node {
    int data;
    node *next;
};

class LinkedList {
    node *head;
    node *tail;
    
public:
    LinkedList(){
        head = nullptr;
        tail = nullptr;
    };
    
    void createNode(int value);
    void display();
};

void LinkedList::createNode(int value){
    node *temp = new node;
    temp->data = value;
    temp->next = nullptr;
    
    if(head == nullptr){
        head = temp;
        delete temp;
        temp = nullptr;
    } else {
        cout << "List is not empty!!" << endl;
    }
};

void LinkedList::display() {
    node *displayNode = new node;
    displayNode = head;
    while(displayNode != nullptr)
    {
        cout<<displayNode->data<<"\t";
        displayNode=displayNode->next;
    }
}

int main(){
    LinkedList *list1 = new LinkedList();
    list1->createNode(4);
    list1->createNode(5);
    
    list1->display();
};





我尝试过:



我已经尝试过编译和调试。



What I have tried:

I have tried compile and debugging.

推荐答案

你还没有完成编码。从技术上讲,如果你已经完成了无bug的任何操作,你的输出就会有

You have not finished coding. Technically, if you have finished whatever you have done bug free, your output would have
List is not empty!!
4





让我们专注于你的 createNode 功能



Let's focus at your createNode function

void LinkedList::createNode(int value){
    node *temp = new node;
    temp->data = value;
    temp->next = nullptr;
    
    if(head == nullptr){
        head = temp;
        delete temp; // if you delete this head variable become invalid. remove this
        temp = nullptr;
    } else {
        // you have not implement what would happen if the list is not empty.
        cout << "List is not empty!!" << endl;
    }
};


这篇关于为什么C ++的行为不同于debuging?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆