类中的私有指针在方法中更改时不会更新
Private pointer in class doesn't update when changed in method
我有这些类(为了可读性而剥离)
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(...);
任何形式的间接都会增加错误、复杂性和不可读性的风险。你的问题就是一个很好的例子!
这是我第一次看到。也许还有更多。
希望这是一个切入点。
相关文章:
- 指针没有更新它在void函数内部指向的值
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 在删除之前更新一组元素指针中的元素
- C++ - 更新指针中的值被覆盖
- 在这种情况下,当尝试从单独的类更新变量时,我是否需要使用指针?
- 当矢量改变容量时,有什么方法可以更新指针/参考值
- 在构造函数中更新指针向量时出现问题
- C++ 指针问题 - 通过方法更新指针
- 是否可以使用一系列智能指针来自动通过其索引更新其值
- 优先级队列实现为单一链接,无法更新插入的指针转换
- 线程更新全局指针时对全局指针的影响
- 用类方法更新指针的困难
- 通过指针更新矢量的元素
- 使用指针对指针可以解决类成员不更新的问题吗?如果是,如何
- 指向节点的指针不更新节点属性
- 在函数之间传递时指针未更新
- 已更新:从函数返回指向数组的指针
- 使用引用更新智能指针
- 如果通过指针分配,C++ vector.size() 不会更新
- C++指针未更新值