gpt4 book ai didi

C++丢失链表中保存的变量数据

转载 作者:行者123 更新时间:2023-11-28 00:17:19 25 4
gpt4 key购买 nike

我使用链表来存储用户输入,然后使用他们的输入进行计算。当我尝试使用链表时,调试显示链表是空的。

第一个函数是 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

最佳答案

您在这两种方法中都使用了局部变量 rootconductor,而不是类成员。您没有提供类声明来查看此类成员是否存在,但即使存在,它们也会被使用相同名称的局部变量覆盖。局部变量的值不在不同的函数和方法之间共享,也不在同一函数/方法的不同调用之间共享。这就是为什么它们被称为本地

关于C++丢失链表中保存的变量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29439627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com