将指针类分配给新类,C++

Assigning pointer classes to new Class, C++

本文关键字:新类 C++ 分配 指针      更新时间:2023-10-16

我来自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?

如果我理解正确,你可以这样写你的Node类C++。

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,因为整数中的所有值都是有效的。