-1

我写了 C++ 代码,这似乎没有错。我使用 Code::Blocks 作为 IDE,它没有给我任何警告或任何错误,但是当我运行它时,它给了我一个框,说我的 exe 文件没有响应。

我的代码如下:

头文件:

// DVD_App.h - Header File

#include <string>
#include <map>

using namespace std;

enum Status {ACTIVE, INACTIVE};

class Customer {
    private:
        string id;
        string name;
        string address;
        Status status;

    public:
        Customer (const string&, const string&, const Status);
        string &getId () { return id; }
};

class CustomerDB {
    private:
        static map<string, int> idList;

    public:
        static void addNewToIdList (const string &threeLetterOfName) {
            idList.insert(pair<string, int>(threeLetterOfName, 0));
        }

        static bool doesThreeLettersOfNameExist (const string &threeLetterOfName) {
            map<string, int>::iterator i = idList.find(threeLetterOfName);
            if ((i->first).compare(threeLetterOfName) != 0)
                return false;
            return true;
        }

        static int nextNumber (const string &threeLetterOfName) {
            map<string, int>::iterator i = idList.find(threeLetterOfName);
            ++(i->second);
            return i->second;
        }
};

源代码:

// DVD_App.cpp - C++ Source Code

#include <iostream>
#include <string>
#include "DVD_App.h"

using namespace std;

map<string, int> CustomerDB::idList;

Customer::Customer (const string &cName, const string &cAddress, const Status cStatus) : name(cName), address(cAddress), status(cStatus) {
    string threeLetters = name.substr(0, 3);
    if (CustomerDB::doesThreeLettersOfNameExist(threeLetters))
        threeLetters += "" + CustomerDB::nextNumber(threeLetters);
    else {
        CustomerDB::addNewToIdList(threeLetters);
        threeLetters += "0";
    }
}

int main () {
    Customer k ("khaled", "beirut", ACTIVE);
    cout << k.getId() << endl;

    return 0;
}

我想首先检查我的 CustomerDB 类是否正常工作,但我不能,因为程序没有运行。任何帮助,将不胜感激。

4

2 回答 2

2

idList最初是空的,所以当你调用doesThreeLettersOfNameExist迭代器时,i你返回的find()将是end()你可能不会取消引用的迭代器。

于 2012-04-27T14:04:25.553 回答
1

您应该检查函数 doesThreeLettersOfNameExist if i == idList.end()。如果发生这种情况,您将无法检查if ((i->first).compare(threeLetterOfName) != 0). 顺便说一句,这发生在第一次迭代中。也将其添加到 nextNumber。

于 2012-04-27T14:04:37.657 回答