【发布时间】:2016-05-11 18:26:47
【问题描述】:
我正在开发一个插入、删除银行账户的程序。
这是我的 .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?因为我在代码中看不到我的错。
【问题讨论】:
-
使用调试器时,
Account *_head的值是多少? -
问题:为什么(一半)侵入式链表实现属于银行账户类?
-
老师告诉我们要这样 :)
-
en.wikipedia.org/wiki/Single_responsibility_principle 此外,除非您需要无锁数据结构或正在做家庭作业,否则基本上没有充分的理由在 C++ 中手动实现链表。
-
请问您有关于插入方法的解决方案吗?
标签: c++ linked-list segmentation-fault