gpt4 book ai didi

c++ - 在 C++ 中将映射指针更改为值时丢弃限定符错误

转载 作者:行者123 更新时间:2023-11-30 01:21:59 24 4
gpt4 key购买 nike

我有这个(简化的)代码可以正常工作。

class T
{
map<string, int>* m;
public:

T()
{
m = new map<string, int>();
}
void get(const string& key, int& val) const
{
val = (*m)[key];
}
}

当我把指针变成值时,

class T
{
map<string, int> m;
public:

void get(const string& key, int& val) const
{
val = m[key];
}

};

我收到此错误消息,出了什么问题?

In member function 'void T::get(const string&, int&) const':
constTest.cpp:12:20: error: passing 'const std::map<std::basic_string<char>, int>'
as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& ...'
discards qualifiers [-fpermissive]
val = m[key];
^

最佳答案

由于get 方法是const,所有数据成员,包括m,都被视为常量。然而,the [] operator on a map 不是常量。使用 at method相反,它有一个 const 重载:

val = m.at(key);

关于c++ - 在 C++ 中将映射指针更改为值时丢弃限定符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com