使用具有给定 .h 文件 c++ 的结构类创建城市链表

Creating a linked list of cities using a struct class with given .h file c++

本文关键字:结构 创建 链表 城市 c++ 文件      更新时间:2023-10-16
#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结构,请执行以下操作:

  1. 将 h 文件作为#include "CommunicationNetwork.h"包含在main.cpp
  2. 使用 main.cpp 编译CommunicationsNetwork.cpp(即在一个二进制文件中链接已编译的文件(

如果你还没有CommunicationsNetwork.cpp并且你的任务是为类CommunicationsNetwork的方法编写定义,你必须从为所有操作设计算法开始(我的意思是,考虑如何构建网络,如何添加城市等(。

默认构造函数可以是:

CommunicationNetwork::CommunicationNetwork()
{
     head = NULL;
     tail = NULL;
}

析构函数(即 CommunicationNetwork::~CommunicationNetwork() ( 必须从列表中删除所有元素,并释放分配给元素存储的内存。

请记住在将城市添加到网络时检查headtail的值(添加到空列表可能略有不同,因为在第一个元素之后,head也是一个tail(。

所以,开始写代码,祝你好运!