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

标签 c++ arrays class

我会继续说我不太擅长 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/

相关文章:

c++ stringstream到不同类型的变量

c++ - 在共享内存上分配原子

java - 如何在 kotlin 中使用 MapBuilder 并添加所有值?

php - 在 Woocommerce 3 中访问订单项目保护数据

c++ - 小于函数解引用指针

c++ - move 语义和引用语义

javascript - 仅基于 JavaScript 中的一个属性返回整个对象?

c - 将 for 循环中的值存储到数组中

Java:扩展内部类

java - fragment 内的非法封闭实例