如何正确处理与其所属类类型相同的变量

How to properly handle a variable with the same type as the class it belongs to?

本文关键字:类型 变量 正确处理      更新时间:2023-10-16

我使用下面的两个文件为我的项目。我所指的变量Node parent最初不是指针,但我很快发现由于明显的原因(内存),这不起作用。

所以我把它变成了一个指针。问题是parent在我的代码中似乎没有得到正确处理,所以当我执行像getParent()这样的函数时,我的应用程序最终崩溃了。什么样的修改可以解决这个问题?

Node.h

#include <string>
#include <vector>
#include <iostream>
#include "Action.h"
class Node
{

Node.cpp

#include "stdafx.h"

检查parent是否为nullptr:

bool Node::getParent( Node& node )
{
    if ( parent )
    {
        node = *parent;
        return true;
    }
    else
    {
        return false;
    }
}

注意,您必须实现Node的正确复制构造函数。一种可能的解决方案是返回父节点的指针或引用,但在一些实现中,这是危险的,因为您允许直接访问内部成员。决定什么对你有好处。

只是一个建议:如果你使用std::sharer_ptr或std::unique_ptr,一些实现会容易得多。

您应该在区分之前检查parent是否为null。

将getParent的签名转换为:

Node* Node::getParent()
Node* Node::getParent() {
    return parent;
}

在你的应用程序中,当你访问它时,先检查。

Node * parent = getParent();
if(parent==nullptr){
    cout << "parent is nulln";
    raise error;
}else{
    // do whatever you want
}