候选函数不可行:第一个参数('const Node *')将失去常量限定符
candidate function not viable: 1st argument ('const Node *') would lose const qualifier
我正在用内置在unordered_map<Node*, unordered_set<Edge>>
数据结构中的c++编写一个diggraph(有向图)类,其中Node和Edge是我自己定义的两个结构体。在课上我写了一个containsNode()
方法来搜索图中是否有Node
。这是containsNode()
方法体:
bool DiGraph::containsNode(const Node * n) const {
auto::const_iterator it = digraph.find(n);
return (it == digraph.end());
}
digraph
是类型为unordered_map<Node*, unordered_set<Edge>>
的diggraph的私有成员。
但是,编译器生成以下错误:
error: no matching member function for call to 'find'
auto::const_iterator it = digraph.find(n);
candidate function not viable: 1st argument ('const Node *') would lose const qualifier
const_iterator find(const key_type& __k) const {return __t...
但是,如果我将方法声明为bool DiGraph::containsNode(Node* n) const {...}
(唯一的区别是从参数列表中删除了const
关键字),那么没有编译错误。
我检查了c++文档,看到unordered_map
容器中的find()
方法声明具有const
关键字:
std::unordered_map::find
const_iterator find(const Key& key) const;
所以我认为不应该有编译错误,那么为什么我得到一个?
find()
看起来像这样:find(const T& key)
如果T
是Node*
,那么Node*
必须是const
。但是请注意,指针必须是const
,而不是containsNode(const Node * n)
所指向的值。find()
不能保证n
所指向的值不会改变,这违反了const Node * n
。
const
指针。你可以投,但对const
的尊重到此为止!我的建议是,重新考虑你是如何做这件事的。
用集合更容易可视化。更少的开销,同样的结果。
#include <set>
using namespace std;
class A
{
};
set<A*> test;
void func1(A *const a) // pointer is const
{
test.find(a); //Compiles, but not what you want.
A b;
a = &b; // Doesn't compile. Can't change where a points
*a = b; // compiles. Value at a is open game
}
void func2(const A * a) // value is const
{
test.find(a); //doesn't compile
A b;
a = &b; // compiles. Can change where a points
*a = b; // does not compile. Can't change what a points at
test.find((A*)a); //Compiles, but holy super yuck! Find a better way!
}
int main()
{
A a;
func1(&a);
func2(&a);
}
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 如何创建长度由常量参数指定的数组
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 为什么对引用的常量引用会失去其恒定性?
- 标准::shared_ptr 失去常量的实例化类型
- 当发生隐式转换时,对象是否失去其常量
- 候选函数不可行:第一个参数('const Node *')将失去常量限定符