0
我使用鏈表來存儲用戶輸入,然後使用它們的輸入進行計算。當我嘗試使用鏈表時,調試顯示列表爲空。C++鏈接列表中保存的變量數據丟失
第一個函數是House對象的構造函數,它創建一個Room鏈表來存儲房間的長度和寬度。
House::House(){
int tempwid = 0;
int templen = 0;
houseSize = 0;
bool cont = true;
node *root;
node *conductor;
root = new node;
root->next = 0;
conductor = root;
if (conductor != 0) {
while (cont){
houseSize++;
tempwid = 0;
templen = 0;
if(tempwid == -1 || templen == -1){
cont = false;
}//End if
else{
cout << "\nPlease enter the dimensions for room #" << houseSize << ". Enter a -1 when you are finished.";
cout << "\nWidth? ";
cin >> tempwid;
cout << "Length? ";
cin >> templen;
if(tempwid == -1 || templen == -1){
cont = false;
}//End if
else{
conductor->width=tempwid;
conductor->length=templen;
conductor->next = new node;
conductor = conductor->next;
conductor->next = 0;
}//End else
}//End else
}//End while
conductor->next = new node;
conductor = conductor->next;
conductor->next = 0;
}//End if
}//End constructor
該功能將只取所有房間的長度和寬度,並計算總房子的面積。
double House :: calculateTax(double tax){
node *root;
node *conductor;
double totalArea = 0;
int i = 0;
conductor = root;
while (conductor->next!=0){
cout <<"Length: " << conductor->length;
cout <<"Width: " << conductor->width;
totalArea += conductor->length * conductor->width;
conductor = conductor->next;
}//End while
totalArea *= tax;
return totalArea;
}//End Function
您的鏈接列表中有** **房間嗎?如果是這種情況,你可以期望'while(conductor-> next!= 0)'立即變爲false。這應該是'while(conductor)'。並且'node * root;'根本沒有在*'House :: House'或'calculateTax'中本地聲明。該decl隱藏了成員變量'root'。 (有*是*成員變量'root',*右*)? – WhozCraig 2015-04-03 21:09:43