C++ 代码的异常行为

Irregular behavior of c++ code

本文关键字:异常 代码 C++      更新时间:2023-10-16

我写了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 类是否正常工作,但由于程序未运行,因此我无法正常工作。任何帮助将不胜感激。

您的idList最初是空的,因此当您调用doesThreeLettersOfNameExist迭代器时,i您得到的返回find()将是您不能取消引用的end()迭代器。

你应该签入函数doesThreeLettersOfNameExist如果i == idList.end()。如果发生这种情况,您将无法检查if ((i->first).compare(threeLetterOfName) != 0) 。顺便说一下,这发生在第一次迭代中。同时将此添加到下一个数字。