C++ 使用枚举 class 对象分配 std::map 值
C++ Assign std::map values with enum class object
考虑以下代码。
在我的真实案例中,我有这样的事情:
typedef enum
{
vehicle,
computer,
} Article;
这就是我要构建的内容:
enum class status{
notPaid,
paid,
};
struct S {
status status_vehicle;
status status_computer;
std::map<Article, status> mymap =
{
{vehicle, S::status_vehicle},
{computer, S::status_computer},
};
};
int main ()
{
Article a1 = vehicle;
S::mymap.at(a1) = status::paid; // this line doesn't work
}
但是,最后一行 (S::mymap.at(a1) = status::paid
;) 不起作用。我尝试了不同的方法,例如使用 std::map
的 find()
函数。我收到错误 "assignment of member std::pair<Article, status>::second
in read only object".
有人知道怎么做吗?也可能如何以更好的方式设计整体? (全部来自 "And that is what I'm trying to construct" 行)。
此外,我更愿意使用 unordered_map
而不是 map
但没有用。谢谢
因为mymap
不是静态的。
你可以这样做:
Article a1 = vehicle;
struct S mystruct;
mystruct.mymap.at(a1) = status::paid;
或将static
添加到结构中的成员:
struct S {
status status_vehicle;
status status_computer;
static std::map<Article, status> mymap;
};
但是当使用静态时,你必须在 struct S
的声明之外初始化 mymap
并且你不能使用 struct
的非静态成员
std::map<Article,status> S::mymap={
{vehicle,S::status_vehicle}
};
A static member is shared by all objects of the class. All static data
is initialized to zero when the first object is created, if no other
initialization is present
在你的例子中逻辑上并不好
因为myMap
是非静态的,所以不能像静态变量那样赋值。
您可以这样更改代码:
int main ()
{
Article a1 = vehicle;
S ss;
ss.mymap.at(a1) = status::paid;
}
考虑以下代码。 在我的真实案例中,我有这样的事情:
typedef enum
{
vehicle,
computer,
} Article;
这就是我要构建的内容:
enum class status{
notPaid,
paid,
};
struct S {
status status_vehicle;
status status_computer;
std::map<Article, status> mymap =
{
{vehicle, S::status_vehicle},
{computer, S::status_computer},
};
};
int main ()
{
Article a1 = vehicle;
S::mymap.at(a1) = status::paid; // this line doesn't work
}
但是,最后一行 (S::mymap.at(a1) = status::paid
;) 不起作用。我尝试了不同的方法,例如使用 std::map
的 find()
函数。我收到错误 "assignment of member std::pair<Article, status>::second
in read only object".
有人知道怎么做吗?也可能如何以更好的方式设计整体? (全部来自 "And that is what I'm trying to construct" 行)。
此外,我更愿意使用 unordered_map
而不是 map
但没有用。谢谢
因为mymap
不是静态的。
你可以这样做:
Article a1 = vehicle;
struct S mystruct;
mystruct.mymap.at(a1) = status::paid;
或将static
添加到结构中的成员:
struct S {
status status_vehicle;
status status_computer;
static std::map<Article, status> mymap;
};
但是当使用静态时,你必须在 struct S
的声明之外初始化 mymap
并且你不能使用 struct
std::map<Article,status> S::mymap={
{vehicle,S::status_vehicle}
};
A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present
在你的例子中逻辑上并不好
因为myMap
是非静态的,所以不能像静态变量那样赋值。
您可以这样更改代码:
int main ()
{
Article a1 = vehicle;
S ss;
ss.mymap.at(a1) = status::paid;
}