有人可以解释为什么以下代码编译失败并显示消息“将‘const apple’作为‘int apple::foo()’的‘this’参数传递并丢弃限定符”,以及如何解决它。
#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
using namespace std;
/*
*
*/
class apple{
private:
int a,b,c,d;
public:
int foo(){
return a+b+c+d;
}
};
class ball{
private:
map<apple,string> mp;
public:
void foo2(){
for(map<apple,string>::iterator it = mp.begin();it!=mp.end();++it){
cout<<it->first.foo()<<endl;
}
}
}
int main(int argc, char** argv) {
return 0;
}
最佳答案
对我有用:(在 foo() 末尾和 ; 在 ball 类末尾添加 const)。 apple 类是 std::map 中的一个键,声明为 const: typedef pair value_type;所以访问 key 也应该声明为常量。
#include <map>
#include <iostream>
using namespace std;
class apple{
private:
int a,b,c,d;
public:
int foo() const {
return a+b+c+d;
}
};
class ball{
private:
map<apple,string> mp;
public:
void foo2(){
for(map<apple,string>::iterator it = mp.begin();it!=mp.end();++it){
cout<<it->first.foo()<<endl;
}
}
};
int main(int argc, char** argv) {
return 0;
}
关于c++ - 作为映射键的对象在 cpp 中变为 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714572/