如何重写 "node->left->key" 将 -> 替换为“(*)”。在 C++ 中?
How to rewrite "node->left->key" replacing -> with "(*)." in C++?
我不熟悉“->”符号,所以我将其替换为 (*)。 .但是,当我遇到下面的代码行时,我尝试替换它但没有成功。我做错了什么,有没有办法重写它?
我一直收到 "key" 是一个指针的错误,当我重写它时,它不起作用。我已经三次检查我的代码,但我还是不明白。
struct Node{
int key;
Node *left;
Node *right;
};
Node* createNode(int key){
Node *node = new Node();
(*node).key = key;
(*node).left = NULL;
(*node).right = NULL;
return node;
}
int main(){
Node *root = createNode(1);
(*root).left = createNode(9);
cout << root->left->key; // Correct?
cout << " OR ";
cout << ((*root).left).(*key);
// this is where my code goes wrong and if I remove the (*) from key
// and just leave it like .key it's wrong because key has to be a pointer
return 0;
}
我希望输出为“9 OR 9”,但它甚至不让我编译超过那个点。
如果你真的想避免->
运算符,你可以这样写:
cout << (*((*root).left)).key;
...但这写起来很痛苦,读起来也很痛苦,所以它很好地说明了为什么 ->
运算符很有用:)
我不熟悉“->”符号,所以我将其替换为 (*)。 .但是,当我遇到下面的代码行时,我尝试替换它但没有成功。我做错了什么,有没有办法重写它?
我一直收到 "key" 是一个指针的错误,当我重写它时,它不起作用。我已经三次检查我的代码,但我还是不明白。
struct Node{
int key;
Node *left;
Node *right;
};
Node* createNode(int key){
Node *node = new Node();
(*node).key = key;
(*node).left = NULL;
(*node).right = NULL;
return node;
}
int main(){
Node *root = createNode(1);
(*root).left = createNode(9);
cout << root->left->key; // Correct?
cout << " OR ";
cout << ((*root).left).(*key);
// this is where my code goes wrong and if I remove the (*) from key
// and just leave it like .key it's wrong because key has to be a pointer
return 0;
}
我希望输出为“9 OR 9”,但它甚至不让我编译超过那个点。
如果你真的想避免->
运算符,你可以这样写:
cout << (*((*root).left)).key;
...但这写起来很痛苦,读起来也很痛苦,所以它很好地说明了为什么 ->
运算符很有用:)