成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
'this' argument to member function has type 'const', but my function is not actually 'const'
我有一个C++std::map
,用于存储有关连接组件的信息。这是我的BaseStation
类中的一段代码,它是非常基本的
//Constructor
BaseStation(string name, int x, int y){
id = name;
xpos = x;
ypos = y;
}
//Accessors
string getName(){
return id;
}
在我的主代码中,我有一个声明为的地图
map<BaseStation, vector<string> > connection_map;
connection_map
在while循环中更新如下,然后出于我自己的调试目的,我想转储映射的内容。我将一个基站对象附加到地图上(作为关键字(,作为值,我们有一个到基站对象的链接列表:
connection_map[BaseStation(station_name, x, y)] = list_of_links;
list_of_links.clear();
for(auto ptr = connection_map.begin(); ptr != connection_map.end(); ++ptr){
cout << ptr->first.getName() << " has the following list: ";
vector<string> list = ptr->second;
for(int i = 0; i < list.size(); i++){
cout << list[i] << " ";
}
cout << endl;
}
这是我在尝试通过clang++编译代码时遇到的主要错误:
server.cpp:66:11: error: 'this' argument to member function 'getName' has type
'const BaseStation', but function is not marked const
cout << ptr->first.getName() << " has the following list: ";
在VSCode中,cout(cout << ptr->first.getName()
(处的工具提示高亮显示如下:
the object has type qualifiers that are not compatible with the member
function "BaseStation::getName" -- object type is: const BaseStation
我不明白发生了什么,因为getName()
函数肯定不是常量,我也不能将BaseStation
对象声明为const。如果有人能帮我,那就太好了。谢谢
std::map
将密钥存储为const
。
value_type
std::pair<const Key, T>
这意味着当您从map
(如ptr->first
(获得密钥时,您将获得const
BaseStation
。
我认为您应该将BaseStation::getName()
声明为const
成员函数,因为它不应该执行修改。
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 使用 std::string () const 函数启动线程或未来
- 如果我在 const 函数上使用指针,我可以返回什么?
- 为什么 const 函数返回左值而不是右值?
- 当我调用 main 中使用 const 对象的 const 函数时,不断出现错误
- 在 const 对象上调用非 const 函数
- 析构函数是否可以在 const 对象上调用非 const 函数
- C/C++ 如何在一次函数调用中交出 const 函数指针或简单指针
- 为什么我可以在C 11中使用const函数修改类
- 防止const函数被调用非const对象
- 如果C 中的支架重载运算符被声明为const函数
- C++:防止在 const 函数中更改指针的值
- 从const函数返回非const属性参考
- 调用指针参数从const函数指向的对象的操作员
- 在const函数中调用非CONST成员的非const函数
- 无法将 const 数据类型传递到非 const 函数中
- 这是检查 const 函数(如果是否创建某些内容)的更好方法
- 在 const 函数中从地图中未经选中读取
- 编译器不会为 "const" 和"not-const"函数给出不明确的错误吗
- 通过const函数中的参数索引返回std :: map的值