c++ - 将指针类分配给新类,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?
解决方案
如果我理解正确,你可以用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 不能NULL
或nullptr
因为整数中的所有值都是有效的。
推荐阅读
- mysql - Mysql:如何根据具有多对多关系的另一个表更新表列
- azure - 使用 terraform 的 Azure Databricks 工作区
- docker - Docker 抛出“{binary} not found”错误
- logic - 组合逻辑电路图上的黑点代表什么?
- python - 如何以特定方式将数据框转换为 Python 字典?
- python - 从 numpy 数组创建数据框
- c - 可以使用三元运算符在一行中实现按位设置/重置吗?
- signalr - 如何在 SignalR 上正确覆盖调用方法
- python - PySpark 作业的实施模式
- javascript - HTML 中的不同窗口