c++ - 函数修改未引用的类

标签 c++ class

我正在试验一个链表。我的函数“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/

相关文章:

c# - 不完全确定如何使用接口(interface)进行多重继承 c#

c++ - 如何在不输出新行的情况下更新终端中的输出字段?

c++ - 如何最好地编写使用相同互斥锁的多个函数

html - CSS类命名不同?

flutter - 为什么我们应该在 dart 中使用 static 关键字代替抽象?

javascript - 当 View 被注入(inject)到 Controller 中时,如何从我的 View 类中获取事件监听器以引用 Controller 类中的方法?

java - Lucene:升级旧项目

c++ - 为什么这个复合语句作为由大括号和括号括起来的语句序列似乎不是有效的语句表达式

c++ - 运行 cmake 后出现 undefined reference 错误

html - CSS Class里面的背景图片到<div>