gpt4 book ai didi

C++ 数组类返回奇怪的值

转载 作者:行者123 更新时间:2023-11-30 01:56:23 25 4
gpt4 key购买 nike

我会继续说我不太擅长 C++,所以我的问题很可能只是我错过的语法错误。

无论如何,我有一个程序可以从文本文件中读取值,然后用它们创建一个类对象数组。问题是当我尝试将值返回到 main.cpp 时,我得到了奇怪的、完全错误的值。

我不确定问题出在代码的哪个位置,所以我会尝试发布所有相关部分。

main.cpp

void findRoom(int capacity, int numRoom);

int numRoom = 0;
std::string room;
int seats;
double len, wid;

#define MAX 100
ClassRoom ClassRoomOb[MAX]

int main()
{
ifstream classes("classList.txt");

//Makes a count of how many rooms are in the list and builds an array of objects containing all room info
while (classes >> room >> seats >> len >> wid) { /*Text reads as "ES2.410 110 50 60"*/
numRoom++;
ClassRoomOb[numRoom] = ClassRoom(room, seats, len, wid);
cout << room << " " << seats << " " << len << " " << wid << endl;
}

//Tells the user how many rooms are in the list. For posterity's sake.
ClassRooms ClassRoomsOb(numRoom);
cout << "There are " << ClassRoomsOb.getnumRooms() << " rooms available." << endl;

//For now it's an infinite loop
while (true) {
cout << "Enter MAX capacity: ";
int capacity;
cin >> capacity;
findRoom(capacity, numRoom);
}
}
//Find Room Function. To look up room based on user input. Right now just returns the area of the rooms until the value problem gets fixed.
void findRoom(int capacity, int numRoom){

for(int i=0; i < numRoom; i++)
{
cout << i << ClassRoomOb[numRoom].getAreaPerSeat() << endl;
}

return;

ClassRoom.h

class ClassRoom
{
private:
int numSeats;
double length, width, area;
string roomName;
public:
ClassRoom(std::string room = "", int seats = 0, double len = 0, double wid = 0);
int getSeats();
double getAreaPerSeat();
std::string getClassRoomName();
};

ClassRoom.cpp

ClassRoom::ClassRoom(string room, int seats, double len, double wid){
int numSeats = seats;
double length = len;
double width = wid;
string roomName = room;
double area = width*length;
}
double ClassRoom::getAreaPerSeat(){
return area;
}

std::string ClassRoom::getClassRoomName(){
return roomName;
}

使用此代码 cout << ClassRoomOb[numRoom].getAreaPerSeat() 将为每个对象获取诸如“1.77793e+263”之类的信息。

感谢您提供的任何帮助,即使只是我不擅长编码并且忘记了一些简单的事情。

最佳答案

问题是你的构造函数 ClassRoom::ClassRoom

您正在创建新的局部变量,并为它们赋值,而不是为成员变量赋值。

ClassRoom::ClassRoom(string room, int seats, double len, double wid){
numSeats = seats;
length = len;
width = wid;
roomName = room;
area = width*length;
}

关于C++ 数组类返回奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19842271/

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