gpt4 book ai didi

c++ - 类中的while循环不会执行c++

转载 作者:行者123 更新时间:2023-12-02 10:28:59 32 4
gpt4 key购买 nike

我有一个while循环作为类(class)的一部分。

#include <iostream>
#include <iomanip>
#include <fstream>

struct familyFinance{ //add 3rd member familyFinance;
int acctNos; float Balance; struct familyFinance *nextNodePointer;
struct familyFinance *dynMemory;
};

using namespace std;
class myFinanceClass {
private:
string fileName="";
familyFinance *ptrHead = nullptr;
public:
void setFileName(string){ fileName="Lab5Data.txt";}
void readFileAndBuildLinkedList(){
ifstream Lab3DataFileHandle;


familyFinance *ptrHead=nullptr;
//familyFinance *dynFinancePtr=nullptr;
familyFinance *tempPtr;
tempPtr=ptrHead;

Lab3DataFileHandle.open(fileName.c_str());
while (!Lab3DataFileHandle.eof( )) {
familyFinance *dynFinancePtr= new familyFinance;


Lab3DataFileHandle >> dynFinancePtr -> acctNos;
Lab3DataFileHandle >> dynFinancePtr -> Balance;

// familyFinance *nextNodePointer = nullptr;
if (ptrHead == nullptr) {
ptrHead = dynFinancePtr;
}

else {
tempPtr = ptrHead;


while (tempPtr -> nextNodePointer != nullptr )
tempPtr = tempPtr->nextNodePointer;
tempPtr->nextNodePointer = dynFinancePtr;

}

}
Lab3DataFileHandle.close();


}
void spitThemOut(){
familyFinance *tempNodePtr;
tempNodePtr = ptrHead;
这是While循环
  while (tempNodePtr) {


cout << "Acct, Balance: " << setw(3)
<<ptrHead->acctNos << " " <<ptrHead->Balance << endl;
tempNodePtr = tempNodePtr->nextNodePointer;
}
}
当我从main类中调用该函数时,我知道它可以读取该函数,只是不会执行while循环。我需要更改执行while循环。如果您在答案中举一个例子,那将是徒劳的。感谢您的时间。

最佳答案

如果while循环在方法中并在该类中定义,则该循环将不会执行,导致该语言不允许这样做。类中定义的方法不允许有任何循环。该类中定义的方法还有其他一些限制。可以通过在类中声明方法但在类外定义方法来解决这种情况,如下所示

class myFinanceClass {
... // all the code before spitThemOut()
void spitThemOut();
};

void myFinanceClass::spitThemOut() {
... // code to work
while (tempNodePtr) {
...
}
}

关于c++ - 类中的while循环不会执行c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63091165/

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