我创建了一个全局对象并将其分配为null。当我尝试访问相同的对象时。它说是模棱两可的。我无法找到全局声明有什么问题。基本上,当它为null时,我会产生歧义。但即使我也无法执行NULL检查。
我已经编写了完整的代码。检查以下代码
using namespace std;
class node {
public :
int data;
class node *left,*right;
node(int data)
{
this->data=data;
this->left=NULL;
this->right=NULL;
}
};
class node* head=NULL;
class node* prev=NULL;
void bt2dll(class node *tree)
{
if(tree==NULL)
return ;
//static node *prev=NULL;
bt2dll(tree->left);
if(prev==NULL)
head=tree;
else
{
prev->right=tree;
tree->left=head;
}
prev=tree;
bt2dll(tree->right);
}
void print(node *root)
{
if (root != NULL)
{
print(root->left);
cout<<root->data<<" ";
print(root->right);
}
}
void printList(node *head)
{
while (head)
{
cout<<head->data<<" ";
head = head->right;
}
}
int main()
{
node *root = new node(10);
root->left = new node(12);
root->right = new node(15);
root->left->left = new node(25);
root->left->right = new node(30);
root->right->left = new node(36);
cout << "Inorder Trvaersal of given Tree is:\n";
print(root);
bt2dll(root);
cout << "\nDouble Linked list is:\n";
printList(head);
return 0;
}
prog.cpp:23:5: error: reference to ‘prev’ is ambiguous
if(prev==NULL)
^~~~
prog.cpp:16:13: note: candidates are: node* prev
class node* prev=NULL;
^~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:66:0,
from /usr/include/c++/6/bits/char_traits.h:39,
from /usr/include/c++/6/ios:40,
from /usr/include/c++/6/istream:38,
from /usr/include/c++/6/sstream:38,
from /usr/include/c++/6/complex:45,
from /usr/include/c++/6/ccomplex:39,
from /usr/include/x86_64-linux-gnu/c++/6/bits/stdc++.h:52,
from prog.cpp:1:
/usr/include/c++/6/bits/stl_iterator_base_```
答案 0 :(得分:3)
您的程序使两个坏习惯和危险习惯相互抵触。他们都赢了,你输了。
using namespace std
极其糟糕和危险。永远不要这样做。该指令污染了(通常是全局的)名称空间,而该名称空间可能来自标准库中的成千上万个名称,您可能不了解其中的大多数名称。它们与您自己的名字产生冲突。更糟糕的是,只要您添加完全无害且无关的#include
指令,它们就可以静默更改程序的含义。在您的示例中,全局变量prev
与注入到全局名称空间中的标准函数std::prev
冲突。您可以通过避免两种不良习惯中的任何一种来避免该错误,但这是一次学习两者的好机会。不要错过。