C++ 如何向链接列表中添加内容
我只是对我犯的一个错误有点困惑。我创建了一个名为“SensorNode”的类,每个SensorNode都有一个传感器的链接列表。SensorNode的一个数据成员是名为mySensors的SensorBlock(链表)指针。mySensors应该指向它所在的传感器节点所拥有的传感器链表中的第一个传感器。以下是SensorNode的类声明:C++ 如何向链接列表中添加内容,c++,class,pointers,linked-list,memory-address,C++,Class,Pointers,Linked List,Memory Address,我只是对我犯的一个错误有点困惑。我创建了一个名为“SensorNode”的类,每个SensorNode都有一个传感器的链接列表。SensorNode的一个数据成员是名为mySensors的SensorBlock(链表)指针。mySensors应该指向它所在的传感器节点所拥有的传感器链表中的第一个传感器。以下是SensorNode的类声明: class SensorNode { char* NodeName; int NodeID; LOCATION Node1;
class SensorNode {
char* NodeName;
int NodeID;
LOCATION Node1;
float batt;
int func;
SensorBlock *mySensors;
public:
SensorNode(char *n, float x, float y, float z, int i, float ah);
void print();
void setOK(int o);
int getOK();
void setLOC(float longi, float lat, float h);
int amIThisSensorNode(char *n);
void addSensorToNode(sensor *s);
};
下面是SensorBlock的类声明:
class SensorBlock {
friend class SensorNode;
SensorBlock * LLelement;
sensor * SensEl;
};
我的问题是我的void addSensorToNode(sensor*s)函数。参数s指向应该添加到属于该节点的传感器列表末尾的传感器。我不知道该怎么做,因为我正在创建和添加的不是一个新的传感器,而是一个指向我正在添加的传感器的指针
以下是我目前掌握的情况:
void SensorNode::addSensorToNode(sensor *s) {
if(mySensors == '\0') //mySensors is first initialized to NULL
{
mySensors = s; //I get an error on this line.
}
else {
}
}
我不知道如何修复我在上面这一行中遇到的错误,我也不知道当mySensors不再等于null时,应该在“else”中添加什么。如果我解决了上述错误,我可能能够更好地理解新传感器的添加过程。提前感谢您提供的任何帮助
mySensors=s
应该是mySensors.SensEl=s
因为mySensors是SensorBlock
类型,而s是传感器
void SensorNode::addSensorToNode(sensor *s) {
if(mySensors == NULL) //mySensors is first initialized to NULL
{
mySensors = new SensorBlock();
mySensors->SensEl = s; //I get an error on this line.
mySensors->LLelement = NULL;
}
else {
SensorBlock newBlock = new SensorBlock();
newBlock->SensEl = s;
newBlock->LLelement = NULL;
mySensors->LLelement = newBlock;
}
}
拍菜鸟头的错误,我一定累了,谢谢。我认为它实际上需要我的传感器->传感器=s;但基本思想是一样的。感谢您向我指出,如果不是链表的最开始,我在else中放什么?@Acoustic,编辑了答案,但我认为您可以通过统一sensor类和SensorBlock来简化数据结构。^感谢您添加了else语句!不幸的是,我得到了一个错误:“从'SensorBlock*'到'SensorBlock'没有可行的转换”。知道那是什么意思吗?关于统一你是对的,但不幸的是这是一个作业,我不能改变课程:/