C++ 我的菜单中未处理的异常
目前我的代码中有一个未处理的异常,我不知道为什么。这是我第一次在一起使用多个类 目前,我正在尝试将用户输入放入另一个类的字符串中。我正在尝试将用户输入输入到下面类中名为name的字符串中C++ 我的菜单中未处理的异常,c++,class,exception,getline,C++,Class,Exception,Getline,目前我的代码中有一个未处理的异常,我不知道为什么。这是我第一次在一起使用多个类 目前,我正在尝试将用户输入放入另一个类的字符串中。我正在尝试将用户输入输入到下面类中名为name的字符串中 #ifndef SHIP_H #define SHIP_H #include "ApplicationMenu.h" #include <string> class Ship { public: Ship(void); ~Ship(void); std::string _s
#ifndef SHIP_H
#define SHIP_H
#include "ApplicationMenu.h"
#include <string>
class Ship
{
public:
Ship(void);
~Ship(void);
std::string _size;
std::string _shipName;
std::string name;
};
#endif
\ifndef SHIP\u H
#定义船舶
#包括“ApplicationMenu.h”
#包括
班轮
{
公众:
船舶(无效);
~船舶(无效);
std::字符串大小;
std::string\u shipName;
std::字符串名;
};
#恩迪夫
进入以下在main中运行的函数
#include "ApplicationMenu.h"
#include "Ship.h"
#include <string>
#include <sstream>
class Ship;
#include <iostream>
using namespace std;
ApplicationMenu::ApplicationMenu(void) { userChoice = 0; }
ApplicationMenu::~ApplicationMenu(void) { }
void ApplicationMenu::displayMenu() {
cout << "Welcome to the Port." << endl << "Please select one of the
following options : " << endl
<< "1: Dock Ship" << endl;
cin >> userChoice;
switch (userChoice)
{
case 1:
Ship* ship;
ship->name;
cout << "Please enter the name of your ship your wish to dock: ";
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, ship->name);
cout << ship->name;
break;
}
}
#包括“ApplicationMenu.h”
#包括“Ship.h”
#包括
#包括
二等船;
#包括
使用名称空间std;
ApplicationMenu::ApplicationMenu(void){userChoice=0;}
ApplicationMenu::~ApplicationMenu(void){}
无效应用程序菜单::显示菜单(){
您可能有一个未初始化的指针Ship*Ship;
。您需要使用Ship*Ship=newship();
或将ship声明为ship ship;
ship*ship是一个统一的指针,指向随机内存位置,然后尝试访问该位置。您应该始终初始化指向nullptr或有效对象的指针,以防止未定义的行为
Ship* s( new Ship );
这看起来确实是个问题,但我不完全清楚他到底是怎么写这段代码的。userChoice
在构造函数之外的任何地方都不会更新,应该一直更新0@dwcanillas我假设他在这里没有显示的代码中更新了userChoice
,因为发布的代码甚至不会按原样编译o这不是一个完整的示例。很抱歉,我错过了这一点,我从cin>>userChoice;
中获得了userChoice;
感谢您修复了它。我只是在学习指针,所以它对我来说是新的。您应该使用调试器检查这种情况,并逐行检查您的代码。这一代码行ship->name代码>顺便说一句?这是一个字符串,我正试图读取用户输入。是的,我们可以看到。但这行实际上应该做什么?不要偏离我的主要建议!