gpt4 book ai didi

c++ - 什么需要在构造函数中,什么需要在 setter 函数中?

转载 作者:太空宇宙 更新时间:2023-11-04 12:30:28 25 4
gpt4 key购买 nike

目标是输出与第一个程序相同的数据。第一个程序需要手动输入房号和房费。第二个(有问题的)程序要求它自动填充房间号和房间成本,这些房间号和房间成本被硬编码到 main 中的数组中。需要类“room”的默认构造函数来填充数组并添加 setter 函数来设置房间号和成本的值。整个程序的目标是创建数组,填充测试数据,然后列出有关房间的数据。程序 1(手动输入)- 这很好用;

#include<iostream>
using namespace std;

class room
{
int roomNo;
float roomCost;
public:
void GetData ();
void PutData ();
};
void room::GetData ()
{
cout << "\n\tEnter room number : ";
cin >> roomNo;
cout << "\n\tEnter room cost : ";
cin >> roomCost;
}
void room::PutData ()
{
cout << "\n\t\t\t" << roomNo << " \t|\t " << roomCost;
}

int main ()
{
int roomNo;

room roomList[10];

for (roomNo = 0; roomNo < 10; roomNo++)
{
cout << "\nEnter details of " << roomNo + 1 << " room" << endl;
roomList[roomNo].GetData ();
}
cout <<"\n*******************************************************************************";
cout << "\n\t\t\t Room Details";
cout <<"\n*******************************************************************************";
cout << "\n\t\t Room Number \t| Cost per Night";
cout << "\n\t\t--------------------------------------";
for (roomNo = 0; roomNo < 2; roomNo++)
roomList[roomNo].PutData();

getchar ();
getchar ();
}

第二个(有问题的)程序;

#include<iostream>
using namespace std;

class room
{
int roomNo;
float roomCost;
public:
room();
void PutData ();
};
room::room()
{
cout<<"\n\t\t\t"<<roomNo<<" \t|\t "<<roomCost;
}
void room::PutData ()
{
cout << "\n\t\t\t" << roomNo << " \t|\t " << roomCost;
}

int main ()
{
int roomNo[10] = {1,2,3,4,5,6,7,8,9,10};
float roomCost[10] = {100.00, 90.00, 85.50, 80.00, 80.00, 50.00, 50.00, 45.50, 45.50, 40.00};

room roomList[10]; //Statement 3 : Creating Array of 3 Employees

cout <<"\n*******************************************************************************";
cout << "\n\t\t\t Room Details";
cout <<"\n*******************************************************************************";
cout << "\n\t\t Room Number \t| Cost per Night";
cout << "\n\t\t--------------------------------------";

for (int roomNo = 0; roomNo < 10; roomNo++)
roomList[roomNo].PutData();

getchar ();
getchar ();
}

最佳答案

问题是 roomNoroomCost 实际上从未为每个 room 实例设置任何值。该类不会自动从您在 main 中定义的数组中提取数据。

此外,

roomList[roomNo].PutData();

访问未初始化的数据:

void room::PutData ()       
{
cout << "\n\t\t\t" << roomNo << " \t|\t " << roomCost;
}

(构造函数有同样的问题)

解决方案是用正确的数据初始化每个房间。我建议使用构造函数:

room(int _roomNum, float _roomCost) : roomNo(_roomNum), roomCost(_roomCost)
{}

然后使用一个vector来初始化(而不是room roomsList[10])

std::vector<room> rooms;
rooms.reserve(10);
for(size_t i = 0; i < 10; ++i)
rooms.emplace_back(roomNo[i], roomCost[i]);

Live Demo

关于c++ - 什么需要在构造函数中,什么需要在 setter 函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58864808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com