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

时间:2013-11-07 17:12:33

标签: 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&lt;&lt; ClassRoomOb [numRoom] .getAreaPerSeat()会为每个对象提供类似'1.77793e + 263'的内容。

感谢您的帮助,即使这只是我在编码方面做得不好而忘记了简单的事情。

1 个答案:

答案 0 :(得分:4)

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

您正在创建新的局部变量,并为这些变量赋值,而不是分配给成员变量。

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