首页 > 解决方案 > 如何在 C++ 上创建类存储?

问题描述

我有这个代码:

#include <iostream>
#include <string>
#include <map>

namespace Test
{
    class Storage
    {
        public:

        static std::map<std::string, std::string> storageMemory;

        static void Set(std::string name, std::string value)
        {
            if (name.length() == 0 && value.length() == 0) {
                return;
            }

            storageMemory[name] = value;
        }

        static std::string Get(std::string name)
        {
            return storageMemory[name];
        }

    };
}

我的想法:

Test::Storage::Set("key", "value"); // to set value
Test::Storage::Get("key"); // to get value by key

有什么想法吗?

为什么这种结构不起作用?

例如,当我在 PHP 中创建此逻辑时,它工作正常。

请帮帮我!

谢谢!

标签: c++

解决方案


请记住,静态可变成员是危险的并且不是线程安全的。要使用静态成员,您需要从类中实例化它:

#include <iostream>
#include <string>
#include <map>

namespace Test
{
    class Storage
    {
        public:

        static std::map<std::string, std::string> storageMemory;

        static void Set(std::string name, std::string value)
        {
            if (name.length() == 0 && value.length() == 0) {
                return;
            }

            storageMemory[name] = value;
        }

        static std::string Get(std::string name)
        {
            return storageMemory[name];
        }

    };

    std::map<std::string, std::string> Storage::storageMemory = {};
}

推荐阅读