指向根的二叉树指针需要被引用和解引用.为什么
Binary tree pointer to the root needs to be referenced and dereferenced. Why?
我的问题是为什么我需要解引用和引用一个指针下面的代码工作?ref/deref不是互相抵消的吗?如果有人能像我五岁一样解释一下,我会很感激的:)
代码:template <typename T>
class binNode {
private:
T key;
public:
binNode * left;
binNode * right;
binNode * parent;
binNode() {
this->left = NULL;
this->right = NULL;
this->parent = NULL;
}
// arg constructor:
binNode (T key) {
this->key = key;
this->left = NULL;
this->right = NULL;
this->parent = NULL;
}
T getKey() {
return this->key;
}
void setKey(T key) {
this->key = key;
}
};
template<typename T> class Tree {
private:
binNode <T> *root;
public:
Tree() {
this->root = NULL;
}
Tree(binNode <T> * node) {
node->parent = NULL;
this->root = node;
}
/* THIS IS THE PART I DON'T GET */
void addNode(binNode<T> *&x, binNode<T> * node) { // what's up with the *&???
if (x == NULL) {
x = node;
return;
} else if (x->getKey() == node->getKey()) {
node->left = x;
node->parent = x->parent;
x->parent = node;
return;
}
if (node->getKey() < x->getKey()) {
addNode(x->left, node);
} else {
addNode(x->right, node);
}
}
void addNode(binNode<T> * node) {
addNode(this->root, node);
}
binNode<T> * treeSearch(binNode<T> * x, T key) {
if (x == NULL || key == x->getKey()) {
return x;
}
if (key < x->getKey()) {
return treeSearch(x->left, key);
} else {
return treeSearch(x->right, key);
}
}
void printOrdered() {
inorderTreeWalk(root);
cout << endl;
}
void inorderTreeWalk(binNode<T> * node) {
if (node != NULL) {
inorderTreeWalk(node->left);
cout << node->getKey() << 't';
inorderTreeWalk(node->right);
}
}
};
这里是主要功能(不包括#inlude
)
int main() {
Tree<int> T (new binNode<int>(10));
// Tree<int> T = new binNode<int>(10);
T.addNode(new binNode<int> (11));
T.addNode(new binNode<int> (9));
T.addNode(new binNode<int> (8));
T.addNode(new binNode<int> (12));
T.printOrdered();
}
这不是对指针的引用/解引用,它是对指针的引用。这是必要的,因为……
void addNode(binNode<T> *&x, binNode<T> * node) {
if (x == NULL) {
x = node; // ...here...
return;
} else // ...
…您正在将分配给参数x
。
如果你没有通过引用传递指针x
,你将赋值给参数的本地副本:
void addNode(binNode<T> * x, binNode<T> * node) {
if (x == NULL) {
x = node; // this acts on the local copy only, and thus does nothing.
return;
} else // ...
通过指针(没有引用),您可以获得地址的本地副本。这意味着您可以操作指针后面的值(在本例中为*x),该值将发生变化。但是如果你改变了地址本身,这个地址就会表现得像一个本地副本,并且你在离开方法后就失去了地址的改变。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 将代码声明放入字中(引用操作符和解引用操作符混淆)
- 指向根的二叉树指针需要被引用和解引用.为什么
- 指针引用和解引用
- c++中指针的递增和解引用顺序
- 理解引用和解引用操作符
- 使用指针和解引用指针按引用传递
- 直接访问变量(而不是使用指针和解引用)会得到不同的值吗?
- 将映射结构强制转换为void指针和解引用
- c++的引用和解引用
- 同一指令中的引用和解引用