C++ 代码的异常行为
Irregular behavior of c++ code
我写了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)
。顺便说一下,这发生在第一次迭代中。同时将此添加到下一个数字。
相关文章:
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- VisualStudios 会抛出异常,而代码块不会 [C++]
- [longjmp/setjmp]c++ 相同的代码窗口有异常 Linux 没有错误并且运行良好
- 为什么代码段会引发浮点异常?
- 我应该C++自定义异常代码放在哪里?
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- C++中的奇怪异常代码,当用户输入为 23 时,退出值 1,073,740,940(代码:0xc0000374)
- 如何在Visual Studio(2015)中增加堆栈尺寸的堆栈尺寸?异常代码:C00000FD
- 从覆盖范围报告中删除自动生成的异常代码
- 防火墙异常代码仅适用于传出连接
- 需要对异常代码进行解释
- C/C++语言-指针和算术..异常代码:c0000005
- 异常代码"EXC_I386_GPFLT"的含义是什么?
- 单元测试失败,异常代码为c0000005
- 如何使异常代码DRY
- 访问计算机指针时发生访问冲突(c系统异常代码:c0000005),导致应用程序崩溃
- 如何在Windows上诊断异常代码0xc0000409
- 如何在iOS Objective-C中捕获C++异常代码