无法从指针(Node *)类型转换为const指针(const Node *&)

无法用指针(Node *)类型转换为const指针(const Node *&)。在以下代码中:
struct Node
{
	int val;
	int index;
	Node(){}
	Node(int v, int i) :val(v), index(i){}
};

struct CompareNode
{
	bool operator()(const Node *&lhs,const Node *&rhs)const
	{
		return lhs->val > rhs->val;
	}
};

void f()
{
	priority_queue<Node*, vector<Node *>, CompareNode> q;
	for (int i = 0; i < 10; ++i)
	{
		q.push(&Node(i, i + 1));
	}
}

编译代码时,会出现错误:无法将参数 1 从“Node *”转换为“const Node *&”,因为Node* p,表示指针p可变,指针p所指的对象也可变,而const Node *&q,表示指针q可变,但是指针q所指向的对象不可变。我们无法从“Node *p”转换为"const Node *&q",(1)假设p可以转换q,q是p的引用,即q是p的一个别名,p指向的对象是个非const对象,但是q指向的对象是个const对象,一个对象不可能同时是const对象和非const对象。所以编译器不允许从“Node *p”转换为"const Node *&q。传递给bool operator()(const Node *&lhs,const Node*&rhs)const,我们的目的是保证指针不可变,而不是保证指针所指向的对象不可变,所以函数bool operator()(const Node *&lhs,const Node *&rhs)const应该改写为bool operator()(Node *const &lhs,Node *const &rhs)const。也可改写成bool operator()(const Node *const &lhs,const Node *const &rhs)const。代码如下:
struct Node
{
	int val;
	int index;
	Node(){}
	Node(int v, int i) :val(v), index(i){}
};

struct CompareNode
{
	bool operator()(const Node *const &lhs,const Node *const &rhs)const 
	{
		return lhs->val > rhs->val;
	}
};

void f()
{
	priority_queue<Node*, vector<Node *>, CompareNode> q;
	for (int i = 0; i < 10; ++i)
	{
		q.push(&Node(i, i + 1));
	}
}

 

猜你喜欢

转载自blog.csdn.net/yang20141109/article/details/52014522