首页 > 解决方案 > 将指针类分配给新类,C++

问题描述

我来自Java背景。我的java类:

class Node {
    public Node left;
    public Node right;
    public int deep;
    public Point p;  //another class
}

当我尝试将其转换为 C++ 时,我遇到了错误:Field has incomplete type Node. 因此,根据一些在线帮助,我将其转换为以下内容:

class Node {
public:
    Node* left;
    Node* right;
    int deep;
    Point p;  //another class
}

但是我的另一部分代码现在中断了。java代码是:

Node pathNode = new Node();
if (pathNode.left == null) {
    pathNode = pathNode.left;
}

我真的很想知道如何在 C++ 中实现它。到目前为止我在 C++ 中的尝试:

class Node {
public:
    Node* left;
    Node* right;
    int deep;
    Point p;
    Node() {
         this->left = nullptr;
         this->right = nullptr;
         this->deep = NULL;   // not sure correct or wrong
         this->p = NULL      //  not sure correct or wrong
    }

然后是c ++代码的其他部分:

Node pathNode;
if (pathNode.left == nullptr) {
    pathNode = pathNode.left;   //<== here i am stuck exactly.
}

或者如果有更好的方法,你可以建议我。此外,如何将类成员设置为 NULL 或 nullptr?

标签: c++

解决方案


如果我理解正确,你可以用NodeC++ 编写你的类。

class Node {
public:
    Node* left;
    Node* right;
    int deep;
    //Point p;
    
    Node() :
        left(nullptr),
        right(nullptr),
        deep(0)
        /*p()*/ {
    }
};

int main() {
    Node* pathNode = new Node();
    
    if (pathNode->left == nullptr) {
        pathNode = pathNode->left;  
    }
    
    if (pathNode == nullptr) { // check if indeed nullptr
        std::cout << "nullptr"<< std::endl;
    }
    
    return 0;
}

编辑: int 不能NULLnullptr因为整数中的所有值都是有效的。


推荐阅读