有关如何解决此错误的建议

Advice on how to resolve this error.

本文关键字:错误 解决 何解决      更新时间:2023-10-16

你好,我是刚来C++,我正在构建一个模拟兔子群的程序。我有点卡在如何解决这个问题上,如何获取方法来识别我的全局指针变量。当我尝试编译我的程序时,我收到此错误。

enter code here
main.cpp: In function ‘bool ageCheck(BunnyNode*)’:
main.cpp:133:5: error: ‘head’ was not declared in this scope
if(head){
^

我还有几个与此类似的错误。我的印象是,如果我理解为什么会出现这个错误,我将能够解决其他错误。我从 ageCheck() 方法中选择一个错误,该方法应该遍历兔子的链表并检查它们的年龄。 这就是我所拥有的

enter code here
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
//#include "listofbunny.h"
using std::cin;
using namespace std;
typedef struct BunnyNode {
string* name;
int age;
bool gender;
string* color;
bool radioactive_bunny;
BunnyNode *next;
BunnyNode *head;
BunnyNode *tail;
BunnyNode *current;
}
char menu();
int randomGeneration(int x);
void generateFeatures(BunnyNode * newBunny);
void startCheck(int pass);
void sizeCheck(bool& terminate);
bool fatherCheck(BunnyNode * bunny, bool& fatherPresent);
bool motherCheck(BunnyNode * bunny);
bool ageCheck(BunnyNode * bunny);
void addBunnyAge();
void addBabyBunny();
void addBunny();
void addBunny(BunnyNode * mother);
int  mutantCount();
void mutantTransform();
void purge();
string getGender(BunnyNode * bunny);
string getName(BunnyNode * bunny);
int getColonySize();
void printColony();
void printFeature(BunnyNode * bunny);
void printSize();
bool ageCheck(BunnyNode * bunny){
if(head){
if(bunny->age >= MAX_AGE && bunny->radioactive_bunny == false){
return 1;
}
else if(bunny->age >= MAX_MUTANT_AGE && bunny->radioactive_bunny){
return 1;
}
else
return 0;
}
}

典型的链表结构由三部分组成

数据

class Bunny
{
string name; // don't use pointers unless you really, really need them
int age;
bool gender;
string color;
bool radioactive_bunny;
public:
string getGender(); // don't need to know which Bunny anymore because 
// these functions are bound to a particular Bunny
string getName();
...
};

节点

struct Node
{
Bunny data; // we will ignore templates for now. But they are rilly kool!
Node * next; // here is a good time to use a pointer: to point to the next node
Node(): next(nullptr) // node constructor. This really helps. Trust me.
{
}
}

除了他们的数据和指向下一个Node的链接之外,Node什么都不知道。你做Node越笨,你就越安全。另请注意,Node包含数据。这使您可以轻松交换数据,而无需重写整个节点,并为您以后轻松模板化排列列表结构(尽管您可能最好跳到std::list)。

和链表:

class LinkedList
{
Node *head;
Node *tail;
Node *current; // not as useful as you might think
public:
LinkedList(): head(nullptr),tail(nullptr),current(nullptr)
{
}
void add(Bunny & bunny);
void remove(const string & bunnyname);
Bunny & get(const string & bunnyname);
Bunny & getNext(); // current may help here, but look into iterators
...
};

请注意,我们从不让呼叫者在Node。他们可以做一些愚蠢的事情,比如delete它或破坏Node::next.

添加、删除和迭代列表在 Stack Overflow 上被打死了,所以你应该能够找到大量如何做到这一点的例子。例如:使用指针从单向链表中删除项目。在我看来,该链接中有一个非常重要的技巧,值得花时间学习。指针就像火:一个得心应手的仆人,但一个可怕的主人。

获取链表的最大技巧是使用铅笔和纸绘制列表和节点。查看它们是如何连接的。在添加、删除等时逐步重绘列表...所以你可以看到它是如何完成的。然后编写代码以匹配绘图。我知道。说起来容易做起来难,但比毫无计划地把头撞在墙上要容易得多。