1

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

无论如何,我有一个程序可以从文本文件中读取值,然后用它们创建一个类对象数组。问题是当我尝试将值返回给 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;

教室.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();
};

教室.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' 的信息。

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

4

1 回答 1

4

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

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

ClassRoom::ClassRoom(string room, int seats, double len, double wid){
    numSeats = seats;
    length = len;
    width = wid;
    roomName = room;
    area = width*length;
}
于 2013-11-07T17:14:46.153 回答