[英]C++: passing const as 'this' argument … discards qualifiers involving Json
我在運行此代碼時遇到錯誤:
for(auto &group : riskAssess.getTopList()) {
Json::Value thisTopPositionAsJson = addTopPlayersByPosition(group);
topPositionAsJSON.append(thisTopPositionAsJson);
}
我在'for'語句的第二行得到了這個錯誤:
error: passing 'const Json::Value' as 'this' argument of 'Json::Value& Json::Value::append(const Json::Value&)' discards qualifiers [-fpermissive]
我相信我的函數addTopPlayersByPosition
的原型是正確編寫的,'const'在正確的位置:
const Json::Value addTopPlayersByPosition(const TopPlayers &thesePlayers) const;
topPositionAsJSON
是一個JSON對象( Json::Value
),在一個名為RiskBuilder
的類中聲明為private和non-const。 導致錯誤的代碼段是此類的函數。
那么這里出了什么問題? 是JSON變得反復無常嗎?
所以問題是const
被傳遞給對象的成員。 例如
class Foo {
int a;
};
const Foo foo;
// foo.a is considered const aswell
在您的示例中,您有一個聲明為的函數
class RiskBuilder {
Json::Value topPositionAsJSON;
void addRiskResults() const;
}
void RiskBuilder::addRiskResults() const {
// ...
for(auto &group : riskAssess.getTopList()) {
Json::Value thisTopPositionAsJson = addTopPlayersByPosition(group);
// not only is *this considered const here, but also
// this->topPositionAsJSON
// You can't append to a const Json::Value 1)
topPositionAsJSON.append(thisTopPositionAsJson);
}
// ...
}
1)這也解釋了錯誤:
error: passing 'const Json::Value' as 'this' argument of 'Json::Value& Json::Value::append(const Json::Value&)' discards qualifiers
在編寫topPositionAsJSON.append(...)
時將this->topPositionAsJSON
傳遞為'this'
,從而觸發錯誤
所以簡單的解決方法是不要將函數聲明為const:
class RiskBuilder {
Json::Value topPositionAsJSON;
void addRiskResults();
}
void RiskBuilder::addRiskResults() {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.