我正在试验一个链表。我的函数“null”似乎修改了我的列表,即使该列表不是通过引用传递的。我读到这些问题可能发生在作为正常的按值调用参数传递的对象上,并且这是在良好的 OOP 中未将类内的数据声明为公共(public)成员的原因之一。我已经尝试过将空函数作为列表的成员函数并且它工作正常,但我仍然想了解为什么这种方式不能正常工作。 谢谢
#include <iostream>
#include <new>
#include <time.h>
#include <stdlib.h>
using namespace std;
class list{
public:
struct element {
int data;
element* next;
};
element * head;
list(){
head=NULL;
}
~list(){
while (head!=NULL){
element *e = head->next;
delete head;
head = e;
}
cout<<"Destructing..\n";
}
void add (int value){
element *e = new element;
e->data = value;
e->next = head;
head= e;
}
};
void fill10 (class list & l){
for (int i= 0; i<10 ;i++){
l.add((rand()%10)+1);
}
}
bool null (class list l){
if (l.head!=NULL){ return false;}
return true;
}
int main ()
{
srand(time(NULL));
class list l;
fill10(l);
cout<<l.head->data<<endl;
cout<<l.head<<endl;
cout<<endl<<null(l)<<endl;//when I comment this everything works out as expected
cout<<l.head->data<<endl; //this data is not the same anymore after null is called
cout<<l.head<<endl;
return 0;
}
最佳答案
问题是您将参数传递给 null
函数的方式
bool null (class list l){
if (l.head!=NULL){ return false;}
return true;
}
按值传递时,您创建了链表的拷贝。此拷贝将包含与原始相同的 head
指针的拷贝。
当函数返回时,该参数将被销毁,其析构函数将删除原始和拷贝之间共享的所有节点。
您要么必须通过引用传递,要么定义一个复制构造函数来为复制的列表创建新节点。
关于c++ - 函数修改未引用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245136/