c++ - 作为映射键的对象在 cpp 中变为 const

标签 c++ c++11

有人可以解释为什么以下代码编译失败并显示消息“将‘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/

相关文章:

c++ - 为什么这个获取和释放内存栅栏没有给出一致的值?

c++ - Gtkmm TreeView : Accessing dynamically added columns

c++ - 创建 constexpr 模板函数以对 C++ 中的任何容器求和

C++ 现代字符串指针

c++ - 使用静态初始化来注册类

c++ - random_shuffle 修改打乱后的对象 (c++11)

c++ - 支持逗号和错误信息的自定义 `assert`宏

c++ - 将 GUI 添加到非托管/boost C++ 应用程序

c++ - 存储唯一元素的最佳 C++ 方法

c++ - 使用统一初始化语法从函数返回元组