我只是说我不太擅长C++,所以我的问题很可能只是我遗漏的语法错误。无论如何,我有一个程序可以从文本文件中读取值,然后使用它们创建一个类对象数组。问题是当我尝试将值返回到main.cpp时,我得到了奇怪的,完全错误的值。我不确定问题在哪里发生,所以我将尝试发布所有相关部分。 main.cpp void findRoom(int capacity, int numRoom);int numRoom = 0;std::string room;int seats;double len, wid;#define MAX 100ClassRoom 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 谢谢您的帮助,即使只是我不擅长编码并忘记一些简单的东西。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 问题是您的构造函数ClassRoom::ClassRoom您正在创建新的局部变量,并为其分配值,而不是分配给成员变量。ClassRoom::ClassRoom(string room, int seats, double len, double wid){ numSeats = seats; length = len; width = wid; roomName = room; area = width*length;} (adsbygoogle = window.adsbygoogle || []).push({});
10-07 20:21