gpt4 book ai didi

c++ - 错误 : passing ‘constas ‘this’ argument discards qualifiers [-fpermissive]

转载 作者:行者123 更新时间:2023-11-28 05:41:13 35 4
gpt4 key购买 nike

我有一个单例类:

class ObjectModel {
public:
virtual ~ObjectModel();
static ObjectModel& Get();

const AttributeStruct operator [] (const std::string &symbol_path) const {
auto path = split(symbol_path, '.');

if (path.size() != 2) {
throw std::runtime_error(Formatter() << "Path '"
<< symbol_path << "' has a wrong format.");
}

const CipAttributeStruct attr = this->dic[path[0]][path[1]];
if (attr.data == nullptr) {
throw std::runtime_error(Formatter() << "Attribute '"
<< symbol_path << "' isn't found.");
}

return attr;
}
private:
ObjectModel();
ObjectModel( const ObjectModel& );
ObjectModel& operator=( ObjectModel& );

std::map<std::string, std::map<std::string, CipAttributeStruct> > dic = {};
};

用法:

void main() {
auto &m = ObjectModel::Get();

std::cout << *static_cast<uint32_t*>(m["Object1.Attribute"].data);
}

由于错误,我无法编译此代码:

error: passing ‘const std::map, std::map, lynx::cip::CipAttributeStruct> >’ as ‘this’ argument discards qualifiers [-fpermissive] const CipAttributeStruct attr = this->dic[path[0]][path[1]];

我在这里看到很多此类问题,但没有一个对我有帮助。我知道我可以删除 const 限定符来避免这个问题。但我想知道是否有另一种方法。

最佳答案

因为 operator[] 具有潜在的破坏性,所以它不是 const 操作。如果您只想观察 map 的内容,请使用at:

const CipAttributeStruct attr = this->dic.at(path[0]).at(path[1]);

关于c++ - 错误 : passing ‘constas ‘this’ argument discards qualifiers [-fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063942/

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