为什么链表中的插入函数不起作用?(C++)
Why is the insert function in linked list not working ? (C++)
我正在开发一个从银行插入、删除账户的程序。
这是我的.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++的好方法。
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- 我正在开发服务器,ip作为参数传递不起作用