Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 空指针取消引用的解决方法?_C++_Class_Reference_C++17_Nullptr - Fatal编程技术网

C++ 空指针取消引用的解决方法?

C++ 空指针取消引用的解决方法?,c++,class,reference,c++17,nullptr,C++,Class,Reference,C++17,Nullptr,我正在回答一个关于的编程问题,因此不允许使用类代码和post order函数之外的任何内容。这个问题是一个简单的后序遍历问题。我用C++在一段时间之后,因为类结构是用指针作为二进制树的左、右节点写出的,如果我要尝试找到树节点的邻居的值,并且它们恰好是空的,那么我会得到一个分段错误。 以下是我目前的代码: #include <bits/stdc++.h> using namespace std; /* you only have to complete the function g

我正在回答一个关于的编程问题,因此不允许使用类代码和post order函数之外的任何内容。这个问题是一个简单的后序遍历问题。我用C++在一段时间之后,因为类结构是用指针作为二进制树的左、右节点写出的,如果我要尝试找到树节点的邻居的值,并且它们恰好是空的,那么我会得到一个分段错误。 以下是我目前的代码:

#include <bits/stdc++.h>

using namespace std;

/* you only have to complete the function given below.  
Node is defined as  

class Node {
    public:
        int data;
        Node *left;
        Node *right;
        Node(int d) {
            data = d;
            left = NULL;
            right = NULL;
        }
};

*/


    void postOrder(Node *root) {
        if(root->left == nullptr && root->right == nullptr)
        {
            return;
        }
        
        postOrder(root->left);
        postOrder(root->right);
        cout << root->data << endl;
    }

}; //End of Solution
#包括
使用名称空间std;
/*您只需完成下面给出的功能。
节点定义为
类节点{
公众:
int数据;
节点*左;
节点*右;
节点(int d){
数据=d;
左=空;
右=空;
}
};
*/
作废后订单(节点*根){
if(root->left==nullptr&&root->right==nullptr)
{
回来
}
后订单(根->左);
后订单(根->右);
如果(root->left==nullptr&&root->right==nullptr)
不能充分检查是否为
nullptr
:因此,如果只有一个节点是
nullptr
,则程序的行为是未定义的

if (root->left) postOrder(root->left);
if (root->right) postOrder(root->right);
是一个修复;完全删除第一个
if
语句


另一种修复方法可能是在函数本身的开头检查if(root),这取决于函数最初的调用方式。

在延迟之前,您应该检查指针:

void postOrder(const Node *root)
{
    if (root == nullptr) {
        return;
    }
    postOrder(root->left);
    postOrder(root->right);
    std::cout << root->data << std::endl;
}
void postOrder(常量节点*根)
{
if(root==nullptr){
回来
}
后订单(根->左);
后订单(根->右);

std::cout data解决方法是:不要取消对空指针的引用。检查
root
而不是它的子项。
#include
使用命名空间std
是两个你应该马上改掉的习惯。使用你需要的头。使用
std:
前缀。