c++ - 如何在 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 中创建此逻辑时,它工作正常。
请帮帮我!
谢谢!
解决方案
请记住,静态可变成员是危险的并且不是线程安全的。要使用静态成员,您需要从类中实例化它:
#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 = {};
}
推荐阅读
- apache-commons-httpclient - Apache HttpClient 中的 NTLM 身份验证
- html - 将html表单相乘
- r - 添加其他图层时,一些热图标签不可见(例如,使用 add_trace)
- rest - Azure Data Lake Storage Gen2 REST API - 列出文件系统 - “代码”:“AuthorizationPermissionMismatch
- ibm-cloud - 如何使用 IBM IAM 访问我的 Cloudant 实例?
- android-studio - 如何增加 Android Studio 同步超时
- c# - 如何为 COM 互操作注册 .NET 5 ClassLibrary
- python - Django SortedManyToManyField 执行重新排序
- spring - Spring Batch Chunk回滚失败并导致重复记录
- html - 为什么当我们将 null 或 undefined 作为值传递时输入值不会改变?