将指针作为私有数据成员传递到 Main 中的成员函数中

Passing a pointer as a private data member into a member function in Main

本文关键字:Main 函数 成员 指针 数据成员      更新时间:2023-10-16

我正在为学校解决一个问题,我正在对存储在线性链表中的值求和。

我有一个定义节点的结构。它有一个数据部分和一个指向 next 的指针。

我有一个类,该类具有在公共部分中处理列表的函数,在私有部分中具有一个名为head的指针。

我在实现文件中实现了一个递归函数来对值求和。 它以node*为论据。

我的问题是,如果它是私有数据成员,如何将该head指针传递到main()中的函数中?

我已经成功地迭代实现了这一点,所以请假设该列表在 main() 中成功实例化。我只是不知道如何将指针从那里传递到我的函数中。

你不把它传进去。该类已经拥有它。如果可以的话,你的班级应该是这样的:

class Foo {
    node* _head;
    node* _tail;
public:
    Foo() : _head(nullptr), _tail(nullptr) {}
    ~Foo() {
        while(_head != nullptr) {
            node* temp = _head;
            _head = _head->next;
            delete temp;
        }
    }
    void insert(const int arg) {
         if(_head = _nullptr) {
             _head = new node(arg);
             _tail = _head;
         } else {
             _tail->next = new node(arg);
             _tail = _tail->next;
         }
    }
    int sum() const {
        int total = 0;
        for(auto i = _head; i != nullptr; i = i->next) {
            total += i->val;
        }
        return total;
    }
};

请注意,sum不需要将_head传递给它,因为_head实际上已经是sum作为方法的对象的成员。