使用具有给定 .h 文件 c++ 的结构类创建城市链表
Creating a linked list of cities using a struct class with given .h file c++
#ifndef COMMUNICATIONNETWORK_H
#define COMMUNICATIONNETWORK_H
#include <iostream>
struct City{
std::string cityName;
std::string message;
City *next;
City(){}; // default constructor
City(std::string initName, City *initNext, std::string initMessage)
{
cityName = initName;
next = initNext;
message = initMessage;
}
};
class CommunicationNetwork
{
public:
CommunicationNetwork();
~CommunicationNetwork();
void addCity(std::string, std::string);
void buildNetwork();
void transmitMsg(char *); //this is like a string
void printNetwork();
protected:
private:
City *head;
City *tail;
};
#endif // COMMUNICATIONNETWORK_H
我只是想知道这个.h究竟做了什么/设置,以及我必须如何在我的通信网络中进行.cpp以及我的主要.cpp来构建给定城市的列表。
注意:这段代码最终应该能够将城市添加到列表中,打印出链表中的城市并传输消息,但我目前只是对尝试创建链表感兴趣。
正如我所看到的CommunicationsNetwork.h
有结构体和类的声明,所以CommunicationsNetwork.cpp
必须定义 class CommunicationNetwork
的所有成员方法,如下所示:
#include "CommunicationNetwork.h"
. . . // some other #include directives
CommunicationNetwork::CommunicationNetwork(){
. . .
}
. . .
void CommunicationNetwork::printNetwork()
{
. . .
}
要在您需要main.cpp
中使用类和City
CommunicationNetwork
结构,请执行以下操作:
- 将 h 文件作为
#include "CommunicationNetwork.h"
包含在main.cpp
中 - 使用
main.cpp
编译CommunicationsNetwork.cpp
(即在一个二进制文件中链接已编译的文件(
如果你还没有CommunicationsNetwork.cpp
并且你的任务是为类CommunicationsNetwork
的方法编写定义,你必须从为所有操作设计算法开始(我的意思是,考虑如何构建网络,如何添加城市等(。
默认构造函数可以是:
CommunicationNetwork::CommunicationNetwork()
{
head = NULL;
tail = NULL;
}
析构函数(即 CommunicationNetwork::~CommunicationNetwork()
( 必须从列表中删除所有元素,并释放分配给元素存储的内存。
请记住在将城市添加到网络时检查head
和tail
的值(添加到空列表可能略有不同,因为在第一个元素之后,head
也是一个tail
(。
所以,开始写代码,祝你好运!
相关文章:
- 如何在C++类内存结构中创建"spacer"?
- 创建结构的数组时遇到分段错误
- 如何在 c++ 中创建结构向量的映射
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- C++为API中定义的结构创建超类
- C++ 使用数组结构创建平衡的二叉搜索树
- 使用匿名联合为结构创建空构造函数
- 正确的结构创建
- OPENDDS-从单个IDL结构创建多个主题
- 是否可以使用给定参数为结构创建推力的功能谓词?
- MFC文档/视图体系结构-创建没有初始视图的文档
- 在c++结构创建中更快地执行
- JNA -结构创建错误
- C++中模板结构创建之间的差异
- 无法推送到由静态映射<结构创建的队列,队列>
- 为类/结构创建多个对象
- 如何从模板结构创建二维数组
- 指向从另一个结构创建的数组的指针(不确定措辞是否正确)C++
- 使用结构创建数组