类中的私有指针在方法中更改时不会更新

Private pointer in class doesn't update when changed in method

本文关键字:更新 指针 方法      更新时间:2023-10-16

我有这些类(为了可读性而剥离)

class node {
   public:
   int x;
   node* next;
   node(){}
   ~node(){}
 };
 class intLinkedList{
     public:
         intLinkedList();
         ~intLinkedList();
         void Add (int newX);
     private:
         node* root;
  };

这是Add中的实现

void intLinkedList::Add (int newX){
  node* newNode = new node();
  newNode->x = newX;
  newNode->next = NULL;
  std::cout << "nn" << root << "nn" << std::flush;
  if (root == NULL){
    root = newNode;    
    return;
  }
  node * current;
  current = root;
  while (current->next != NULL){
    current = current->next;
  }
  current->next = newNode;
  return;
}

当我在设置后立即打印出根指向的地址时,它会显示一个有效的地址。但是,下次调用Add时,root再次变为NULL。我无法想象是什么行为导致了这种情况。这在其他地方是绝对不用的。

我完全意识到我缺少一些简单的东西。如果你因为问题很简单而倾向于否决投票,那就去别处吧。这个平台的目的是让程序员在我们有编码头脑时能够团结起来互相帮助。

编辑:这是驱动程序。

#include <string>
#include <iostream>
#include "intLinkedList.h"
using namespace std;
void AddValue(intLinkedList MyList);
void GetValue(intLinkedList MyList);
void InsertValue(intLinkedList MyList);
void DeleteValue(intLinkedList MyList);
void PrintList(intLinkedList MyList);
int main(){
    intLinkedList MyList;
    int Option;
    while (true){
        cout << "nnMain Menun---------nn1) Add Valuen2) See Valuen3)     Insert Value at Positionn4) Delete Value at Positionn5) Print Listn6)     Exitnn";
    cin >> Option;
        switch (Option){
            case 1: AddValue(MyList); break;
            case 2: GetValue(MyList); break;
            case 3: InsertValue(MyList); break;
            case 4: DeleteValue(MyList); break;
            case 5: PrintList(MyList); break;
            case 6: exit(0);
        }
    }
}
void AddValue(intLinkedList MyList){
    int NewValue;
    cout << "What value should be added?n";
    cin >> NewValue;
    MyList.Add(NewValue);
}
void GetValue(intLinkedList MyList){
    int Position;
    cout << "What position do you want the value of?n";
    cin >> Position;
    MyList.Get(Position);
}
void InsertValue(intLinkedList MyList){
    int Position;
    int NewValue;
    cout << "What position do you wnat to insert after?n";
    cin >> Position;
    cout << "nWhat value do you want to insert?n";
    cin >> NewValue;
    MyList.Insert(NewValue, Position);
}
void DeleteValue(intLinkedList MyList){
    int Position;
    cout << "What position do you want to delete?n";
    cin >> Position;
    MyList.Delete(Position);
}
void PrintList(intLinkedList MyList){
    cout << MyList.Print();
}

BTW:我想知道为什么人们要编写链表实现?为什么不使用c++标准库?

void AddValue(intLinkedList MyList);

这将生成一个完整的新MyList项。您应该使用引用!

void AddValue(intLinkedList& MyList);

编辑:

为什么使用

 case 1: AddValue(MyList); break;

而不是:

 MyList.Add(...);

任何形式的间接都会增加错误、复杂性和不可读性的风险。你的问题就是一个很好的例子!

这是我第一次看到。也许还有更多。

希望这是一个切入点。