【发布时间】:2021-08-03 08:03:11
【问题描述】:
我正在学习 C++ 在线课程的最后一部分,但我的一个实验室遇到了困难。该实验室描述了编写一个程序,让用户知道剧院的可用票和已售票。
代码的输出应该是:
AA 101 已售出
AA 102 可用
但是,我继续收到以下输出:
AA 101
AA 102 可用
在 VS Code 中通过调试器运行程序时,我注意到 'sell_seat'() 函数在评估“if(!myticket1.is_sold())”时被跳过。
删除“myticket1.is_sold()”前面的感叹号会得到正确的输出,但不能解决问题。
我的代码哪里出错了?
实验室的先决条件:
该类应包含行、座位号和是否 票是否已售出。定义一个接受为的构造函数 参数行和座位号,并将已售状态设置为 false 构造函数初始化部分。
包括以下成员函数:
A function to check if the ticket has been sold with this signature: bool is_sold(); A function to update the ticket status to sold with this signature: void sell_seat(); A function to print the row, seat number, and sold status delimited by a space with this signature: string print_ticket();
ShowTicket 类
#include <iostream>
#include <string>
using namespace std;
class ShowTicket {
public:
string row;
string seatNum;
string status;
bool is_sold();
void sell_seat();
string print_ticket();
ShowTicket(string sRow, string Num) {
row = sRow;
seatNum = Num;
}
};
bool ShowTicket::is_sold() {
if (row == "AA" && seatNum == "101") {
return true;
}
else {
return false;
}
}
void ShowTicket::sell_seat() {
if (is_sold()) {
status = "sold";
}
else {
status = "available";
}
}
string ShowTicket::print_ticket() {
return row + " " + seatNum + " " + status;
}
主要功能
int main() {
ShowTicket myticket1("AA", "101");
ShowTicket myticket2("AA", "102");
// The sell_seat function is skipped for myticket1, causing the issue
if (!myticket1.is_sold()) {
myticket1.sell_seat();
}
if (!myticket2.is_sold()) {
myticket2.sell_seat();
}
cout << myticket1.print_ticket() << endl;
cout << myticket2.print_ticket() << endl;
return 0;
}
【问题讨论】:
-
使用调试器单步调试代码并观察变量的调试会话的结果是什么?
-
您有什么理由将座位 number 作为字符串?
-
由于座位有两种状态,已售出和可用,您可以将状态设为
bool类型。 -
在我看来
ShowTicket构造函数将行和座位号设置为 AA 和 101,因此if (row == "AA" && seatNum == "101")的结果完全可以预测。我认为您需要在这里更好地解释您的意图。 -
想想
sell_seat函数中的逻辑,以及出售席位的后果。在大多数现实世界的场景中,如果一个座位(已经)售出,你就不能卖掉它。如果您的座位有空,那么出售座位会将其状态更改为“已售出”,还是会这样?