为什么链表中的插入函数不起作用?(C++)

Why is the insert function in linked list not working ? (C++)

本文关键字:C++ 不起作用 函数 链表 插入 为什么      更新时间:2023-10-16

我正在开发一个从银行插入、删除账户的程序。

这是我的.hpp代码:

#ifndef DEF_BANK
#define DEF_BANK
#include <iostream>
using namespace std;
class Bank
{
private:
    class _Account
    {
    public:
        _Account(string, float);
        string getClient();
        float getBalance();
        _Account *getNext();
        void setClient(string);
        void setBalance(float);
        void setNext(Bank::_Account *);
    private:
        string _client; //nom client
        float _balance; // stocke balance du compte
        _Account *_next; // next account
    };
    _Account *_head;
public:
    Bank();
    Bank(string name, float balance);
    _Account *rechercheClient(string);
    float withdraw(string, float);
    float deposit(string, float);
    void createAccount(string, float);
    void insert(string, float);
    void remove(string name);
    float deleteAccount(string);
    void mergeAccounts(string, string);
    void displayAccounts();
};
#endif

这是我的.cpp插入函数:

void Bank::insert(string name, float balance)
{
    _Account *temp(_head);
    //_Account *n = new _Account(name, balance); 
    bool flag(true);
    while(temp)
    {
        if (temp->getClient() == name)
        {
            /* code */
            cout << "DENIED OPERATION! --> "<< name <<"’s account already exists." << endl;
            flag = false;
        }
        temp = temp->getNext();
    }
    if (flag)
    {
        /* code */
        temp->setNext(new _Account(name, balance));
    }
}

为什么当我在main.cpp:中尝试这个

int main()
{
    Bank account_1;
    account_1.insert("Hamza", 1000.0);
}

我有一个分段错误:11?因为我在代码中看不出我的错。

bool flag(true);
while(temp)
{
    if (temp->getClient() == name)
    {
        /* code */
        cout << "DENIED OPERATION! --> "<< name <<"’s account already exists." << endl;
        flag = false;
    }
    temp = temp->getNext();
}
if (flag)
{
    /* code */
    temp->setNext(new _Account(name, balance));
}

这没有道理。一旦temp指向nullptr,控制就离开while循环。然后尝试用temp->setNext(new _Account(name, balance));取消引用该指针。这就是未定义的行为。

正如另一个答案所指出的,您的循环是错误的。如果您更改最后一行:
temp = temp->getNext();

到此:

if (temp->getNext()) {
    temp = temp->getNext();
} else {
    break;
}

然后,循环应该停止在列表中的最后一个元素,而不是列表中最后一个之后的(不存在的)元素。

然而,真正的问题是,你的老师认为这是教初学者C++的好方法。