C ++访问冲突读取位置,类此指针为NULL

时间:2015-03-21 05:07:56

标签: c++

我想得到一些关于我当前项目的帮助,因为我很难理解我的程序到底出了什么问题。我相信问题在于我的构造函数。当我调用成员函数时,它的行为就像我没有初始化我的班级成员一样。

这是我的班级:

class BankList {
public:
    // constructor
    BankList();
    BankList(int size);
    bool isEmpty() const;
    int size() const;
    void insertBankEntry(std::string account, std::string level, std::string lName, std::string fName, float value); // add a single entry to the list
    void insertBankData(std::string fileName); // populate list data from the file
    void deleteBankEntry(std::string key); // delete a single entry
    void findBankEntry(std::string key) const;  // Find and display one element using key
    void checkBankEntry(std::string account);
    void printHashBankData() const; // List data in hash table sequence
    void printHashKeyBankData() const; // List data in key sequence (sorted)
    void printTreeBankData() const; // Print indented tree
    void writeBankData(); // Write data to a file
    void outputHashStatistic() const; // print hash stats
private:
    HashList* hashlist;
    Tree* tree;
    int count; // number of records
    int hashSize;
};

以下是我的构造函数:

BankList::BankList()
{
    HashList* hashlist = new HashList();
    Tree* tree = new Tree();
    count = 0;
    hashSize = 0;
}
BankList::BankList(int size)
{

  HashList* hashlist = new HashList(size);
  Tree* tree = new Tree();
  count = 0;
  hashSize = size;
}

我试图打电话的功能:

void BankList::insertBankEntry(string account, string level, string lName, string fName, float value)  // add a single entry to the list
{
    BankCustomer* customer = new BankCustomer(account, level, lName, fName, value);
    hashlist->insert(customer);
    tree->Insert(customer);
    count++;
}

但是,如果我将此代码放在我的函数中,它确实有效。

if (!tree || !hashlist)
{
  tree = new Tree();
  hashlist = new HashList();
}

主:

int size = getSize();
BankList* list = new BankList(size);
list->insertBankEntry("123412341234", "Gold", "Jonhson", "Steve", 1234.45);

提前致谢!

1 个答案:

答案 0 :(得分:2)

在构造函数中,您隐藏了成员变量(通过声明与成员同名的变量),因此您的成员变量保持未初始化

HashList* hashlist = new HashList(); // hiding the member variable this->hashlist
Tree* tree = new Tree(); // hiding the member variable this->tree

只需使用

hashlist = new HashList();
tree = new Tree();

在构造函数内部。