c++ - 创建 C++ 类的新实例,结果重复

标签 c++ oop singly-linked-list

我是 C++ 新手。我正在尝试实现一个 LinkedList,为此我创建了两个类 NodeLinkedList

我创建了一些测试函数。一个用于测试 Node 创建,另一个用于测试 LinkedList 中的 isEmpty 函数。但是,当我尝试测试它们时。在“testNode()”中创建的最终位于我在LinkedListashead 中创建的同一个节点中。

这可能是一个微不足道的问题,但是作为 C++ 的新手,这个概念对我来说仍然不是很清楚。我想知道为什么它指的是之前创建的同一个实例。

#include <iostream>
#include <assert.h>

using namespace std;

class Node
{
    private:
        int data;
        int next;

    public:

        int getData(){return data;}
        void setData(int new_data) {data = new_data;}

        int getNext(){return next;}
        void setNext(int new_next) {next = new_next;}

};


class LinkedList
{
    Node head;
    Node head2;

    public:

        bool isEmpty()
        {
            if (head.getData() == 0) {return true;}
            return false;
        }

};

void testNode()
{
    Node aNode;
    aNode.setData(15);
    aNode.setNext(23);

    assert (aNode.getData() == 15);
    assert (aNode.getNext() == 23);
}

void testEmptyLinkedList()
{
    LinkedList ll;
    assert (ll.isEmpty() == true);
}

最佳答案

初始化您的数据。

int data = 0;
int next = 0;

Live On Coliru

#include <iostream>
#include <cassert>

using namespace std;

class Node {
  private:
    int data = 0;
    int next = 0;

  public:
    int getData() { return data; }
    void setData(int new_data) { data = new_data; }

    int getNext() { return next; }
    void setNext(int new_next) { next = new_next; }
};

class LinkedList {
    Node head;
    Node head2;

  public:
    bool isEmpty() {
        if (head.getData() == 0) {
            return true;
        }
        return false;
    }
};

void testNode() {
    Node aNode;
    aNode.setData(15);
    aNode.setNext(23);

    assert(aNode.getData() == 15);
    assert(aNode.getNext() == 23);
}

void testEmptyLinkedList() {
    LinkedList ll;
    assert(ll.isEmpty() == true);
}

int main() {
    testEmptyLinkedList();
}

关于c++ - 创建 C++ 类的新实例,结果重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29569758/

相关文章:

c++ - C++链表数据结构中删除挂起

c++ - 我的应用程序是否正在加载 dll 以使用 std::string?

c++ - 我正在尝试使用 C++ 中的 vector 实现(算法简介(CLRS))中的合并排序算法,但数组未排序,

oop - 模型/ View 分离

Java:将一个对象扩展到另一个对象

java - 将对象从列表传输到数组

java - 单链表 : Trying to remove element before a passed type Object paramater

java - 从 j2me 读取图像到 c++

c# - 创建和使用数据库并轻松安装的 GUI

php - 扩展已实例化但没有 'new' 的类