IDE
代码块
mingw32-make 3.82.90
以下是我的程序的调用堆栈
调用堆栈
0 0x45cb6b std :: string :: assign(std :: string const&)() (??:??)
1 0x1 ?? ()(??:??)
2 0xf72ac0 ?? ()(??:?? ??) 3 0x402332 Shop :: initItem(this = 0xf72778) (C:\用户\ Hethann \桌面\ Codeblock_Source \咖啡\ shop.cpp:107)
4 0x4020e3 Shop :: initMenu(this = 0xf72778) (C:\ Users \ Hethann \ Desktop \ Codeblock_Source \ Coffee \ shop.cpp:68)
5 0x402093 Shop :: initShop(this = 0xf72778) (C:\ Users \ Hethann \ Desktop \ Codeblock_Source \ Coffee \ shop.cpp:54)
6 0x401f58 Shop :: Shop(this = 0xf72778) (C:\ Users \ Hethann \ Desktop \ Codeblock_Source \ Coffee \ shop.cpp:46)
7 0x4013c1 main() (C:\用户\ Hethann \桌面\ Codeblock_Source \咖啡\ main.cpp中:10)
#3处出现问题。以下是相关部分的代码片段
bool Shop::initItem()
{
int count = 0, tempPrice;
std::string input;
std::stringstream tempSTRM;
std::vector <Item>::iterator itemITR = menu.items.begin();
Item tempITM;
do
{
std::cout << "Input item name for item[" << count+1 << "]\t:\t";
std::getline(std::cin, input);
if(input == "0")
break;
tempITM.itemName = input;
std::cout << "Input the price for the item[" << count+1 << "]\t:\t";
std::getline(std::cin, input);
tempSTRM.str(input);
tempSTRM >> tempPrice;
tempITM.price = tempPrice;
menu.items.push_back(tempITM);
tempITM = *itemITR; //this line is causing the problem
std::cout << tempITM.itemName << "\t" << tempITM.price << "\n";
itemITR++;
count++;
}while(input !="0");
return false;
}
struct MenuItems
{
std::string menuName;
std::vector <Item> items;
};
typedef struct MenuItems Menu;
struct Item
{
std::string itemName;
int price;
bool promoStatus;
double promoDiscount;
};
typedef struct Item Item;
#include <windows.h> //leftover code from previous experiment
#include <tchar.h> //leftover code from previous experiment
#include "CoffeeShop.h"
using namespace std;
int main()
{
Shop* CoffeeShop = new Shop();
//Other leftover codes
return 0;
}
我的意图:是获取我想要推送的任何内容的输出(因为我正在构建项目,所以一旦其他部分准备就绪,我就可以自信地产生输出。)
由于这会导致SIGSEGV问题,所以我目前的想法是行不通的。通过放置指针对象Item并访问itemITR来尝试它,但它也不起作用。任何人都可以阐明我的错误(在意识形态上),我应该怎么做?
- 编辑 -
Shop::Shop()
{
if(!initShop())
std::cout << "Object creation succeeded!\n";
else
std::cout << "Object creation failed!\n";
}
bool Shop::initShop()
{
if(!initMenu())
{
std::cout << "Object creation succeeded!\n";
return false;
}
else
{
std::cout << "Object creation failed!\n";
return true;
}
}
bool Shop::initMenu()
{
if(!initItem())
{
std::cout << "Object Creation succeeded!\n";
return false;
}
else
{
std::cout << "Object creation failed!\n";
return true;
}
}
流程 - &gt;商店构造函数调用initShop然后initShop调用initMenu,initMenu调用initItem
商城 - &GT; initShop - &gt; initMenu - &gt; initItem
- 编辑2--
解决。加入
itemITR = menu.items.begin();
行后
menu.items.push_back(tempITM);
谢谢!
答案 0 :(得分:3)
使用给定的向量初始化迭代器:
std::vector <Item>::iterator itemITR = menu.items.begin();
然后在向量中插入一些内容:
menu.items.push_back(tempITM);
这个might invalidate迭代器。所以取消引用它是UB并导致段错误