【发布时间】:2020-10-16 17:34:41
【问题描述】:
所以我正在为学校作业执行此单链表实施。在头文件中定义了“评估”结构,“mylinkedlist”对象将保存指向链表头部的指针。这应该是一个简单的项目,但由于某种原因,每当我尝试调用 add 函数时,尽管 a) 没有被调用,并且 b) 在 add 函数被调用之前,head 指针似乎已经改变了
以下是问题的最小重现
//header file
#pragma once
#ifndef MYLINKEDLIST_H
#define MYLINKEDLIST_H
#include <iostream>
#include <process.h>
using namespace std;
const int maxSize = 20; // size string
struct Evaluation
{
char student[maxSize] = { 'a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t' };
int grade;
Evaluation *next;
};
class myLinkedList {
private:
Evaluation *head;
public:
myLinkedList(Evaluation *);
Evaluation *add(Evaluation *, int &);
Evaluation * returnHead();
};
#endif#pragma once
//mylinkedlist.cpp
#include "pch.h"
#include "myLinkedList.h"
#include <iostream>
#include <string>
myLinkedList::myLinkedList(Evaluation *h) {
this->head = h;
}
Evaluation * myLinkedList::returnHead() {
return this->head;
}
Evaluation * myLinkedList::add(Evaluation *c, int &b) {//a is the first element
Evaluation *pointer = this->head;
cout << "head in the beginning " << this->head->grade << endl;
cout << "pointer in the beginning " << pointer->grade << endl;
bool y = b == 0;
cout << "b==0 " << y << endl;
if (b == 0) {
pointer = this->head;
this->head = c;
this->head->next = pointer;
cout << "head after if " << this->head->grade << endl;
}
return this->head;
}
//main
#include "pch.h"
#include "myLinkedList.h"
#include <iostream>
#include <string>
int main() {
Evaluation *first = new Evaluation();
int choice;
int grade = 0;
int number = 0;
first->grade = 20;
myLinkedList *list = new myLinkedList(first);
cout << "list head is " << list->returnHead()->grade << endl;
Evaluation *tempt = new Evaluation();
do
{
cout << "please enter the grade of student : ";
cin >> grade;
cout << "list head is 2nd " << list->returnHead()->grade << endl;
tempt->grade = grade;
cout << "list head is 3rd " << list->returnHead()->grade << endl;
list->add(tempt, number); // added element, index
number++;
} while (true);
return 0;
}
尽管没有调用头部,但看看头部是如何在“列表头部是 2nd”和“列表头部是 3rd”之间发生变化的。另一个奇怪的事情是,如果我删除了 add 函数或对 add 函数的调用,尽管在 couts 之后调用了 add 函数,问题还是会消失。
在 add 方法中,if 语句似乎再次成为问题,尽管它位于 cout 行之后并且没有执行(b==0 输出 false)。我知道它与持续存在的问题有关的唯一方法是,如果我删除它,问题就会消失。
【问题讨论】:
标签: c++ pointers struct linked-list singly-linked-list