C++ 通行证;“常量指针”;发挥作用
我已经写了一个程序,在二叉树上执行各种操作。开始时,我设置空根指针,然后调用两个C++ 通行证;“常量指针”;发挥作用,c++,C++,我已经写了一个程序,在二叉树上执行各种操作。开始时,我设置空根指针,然后调用两个insert()函数将新节点添加到树中 最后,我调用search()函数来查找请求的结构节点并返回它 insert()函数接受两个参数—对根指针的引用和常量int键,这两个参数将转换为节点结构并添加到树中 search()函数接受“常量根指针”-而不是引用,因为我想直接对本地指针进行操作,我不想更改它。另一个参数是int key 这是整个计划: #include <iostream> struct
insert()
函数将新节点添加到树中
最后,我调用search()
函数来查找请求的结构节点并返回它
insert()
函数接受两个参数—对根指针的引用和常量int键,这两个参数将转换为节点结构并添加到树中
search()
函数接受“常量根指针”-而不是引用,因为我想直接对本地指针进行操作,我不想更改它。另一个参数是int key
这是整个计划:
#include <iostream>
struct node
{
node *p; // parent
node *left, *right;
int key;
};
void insert(node *&root, const int key)
{
node newElement = {};
newElement.key = key;
node *y = NULL;
while(root)
{
if(key == root->key) exit(EXIT_FAILURE);
y = root;
root = (key < root->key) ? root->left : root->right;
}
newElement.p = y;
if(!y) root = &newElement;
else if(key < y->key) y->left = &newElement;
else y->right = &newElement;
}
node* search(const node *root, const int key)
{
while( (root) && (root->key != key) )
root = (key < root->key) ? root->left : root->right;
return root;
}
int main()
{
using namespace std;
node *root = NULL;
insert(root, 5);
insert(root, 2);
cout << search(root, 5)->key << endl;
return 0;
}
#包括
结构节点
{
node*p;//父节点
节点*左,*右;
int键;
};
无效插入(节点*&根,常量int键)
{
节点新元素={};
newElement.key=key;
节点*y=NULL;
while(根)
{
如果(键==根->键)退出(退出失败);
y=根;
根=(键<根->键)?根->左:根->右;
}
newElement.p=y;
如果(!y)根=&newElement;
如果(keykey)y->left=&newElement;
else y->right=&newElement;
}
节点*搜索(常数节点*根,常数整数键)
{
while((根)&(根->键!=键))
根=(键<根->键)?根->左:根->右;
返回根;
}
int main()
{
使用名称空间std;
node*root=NULL;
插入(根,5);
插入(根,2);
cout key在search
中,变量root
是一个const节点*
。但是,您试图将其作为节点*
返回。您不能这样做,因为这会违反const的正确性。如果您返回一个指向真正const
对象的指针,那么客户端将能够修改该对象。
相反,您需要使函数返回一个const节点*
。或者根
应该只是一个节点*
,根
是const节点*
,返回值是节点*
。它应该更改为const节点*
const node* search(const node *root, const int key);
如果您需要一个搜索
函数返回一个非常量节点
,那么它需要一个非常量节点
参数。您可以提供一个重载以允许这两种可能性
node* search(node *root, const int key);
由于返回的是同一个指针,因此不能有常量参数和非常量返回。请编写两个版本,一个常量,一个非常量
这是证明const_cast正确的少数情况之一。编写两个版本的搜索函数,一个可以使用const_cast调用另一个
const node* search(const node *root, const int key)
{
while( (root) && (root->key != key) )
root = (key < root->key) ? root->left : root->right;
return root;
}
node* search(node *root, const int key)
{
return const_cast<node *>(search(const_cast<const node *>(root), key));
}
const节点*搜索(const节点*根,const int键)
{
while((根)&(根->键!=键))
根=(键<根->键)?根->左:根->右;
返回根;
}
节点*搜索(节点*根,常量int键)
{
返回常量强制转换(搜索(常量强制转换(根),键));
}
好的,root
是常量节点*
,返回值是节点*
。它应该更改为常量节点*
。我认为OP需要能够修改找到的项,所以两个重载可能是个好主意,一个常量,一个非常量。