最長的Hello, World!(C++)

avrox發表於2024-07-27

最長的Hello, World!(C++)

#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <random>

_<typename T>
class Node
{
public:
    T data;
    std::shared_ptr<Node<T>> next;

    Node(const T &value) : data(value), next(nullptr)
    {}
};

_<typename T>
class LinkedList
{
public:
    LinkedList() : head(nullptr)
    {}

    void append(const T &value)
    {
        auto newNode = std::make_shared<Node<T>>(value);
        if (!head)
        {
            head = newNode;
        } else
        {
            auto current = head;
            while (current->next)
            {
                current = current->next;
            }
            current->next = newNode;
        }
    }

    void print() const
    {
        auto current = head;
        while (current)
        {
            std::cout << current->data;
            if (current->next)
            {
                std::cout << " ";
            }
            current = current->next;
        }
        std::cout << "";
    }

private:
    std::shared_ptr<Node<T>> head;
};

class MessageBuilder
{
public:
    MessageBuilder()
    {
        list.append("Hello,");
        list.append("World!");
    }

    LinkedList<std::string> getMessage()
    {
        return list;
    }

private:
    LinkedList<std::string> list;
};

class Printer
{
public:
    Printer() : messageBuilder()
    {}

    void printMessage()
    {
        try
        {
            LinkedList<std::string> messageList = messageBuilder.getMessage();
            messageList.print();
        } catch (const std::exception &e)
        {
            std::cerr << "Error printing message: " << e.what();
        }
    }

private:
    MessageBuilder messageBuilder;
};

class Application
{
public:
    Application() : printer()
    {}

    void run()
    {
        printer.printMessage();
    }

private:
    Printer printer;
};

int main()
{
    Application app;
    app.run();
    return 0;
}

相關文章