如何正确处理与其所属类类型相同的变量
How to properly handle a variable with the same type as the class it belongs to?
我使用下面的两个文件为我的项目。我所指的变量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
}
相关文章:
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 指针数据类型变量如何包含对象?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何为结构类型变量赋值
- 如何将字符类型变量附加到字符串中?
- 共享或私有 openmp 代码中的结构化类型变量
- 有没有办法在 c++ 中制作类型变量?
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 如何检查类中定义的枚举类型变量是否被分配给?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 是否可以在没有结构的情况下创建新的类型变量?
- 为什么类型变量;不调用默认 CTR
- 如何使用CIN将输入整数值获取到char类型变量中
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- Eclipse CDT 打开声明的自动类型变量
- 如何计算长长类型变量中的位数
- 将自动类型变量初始化为零.这种类型安全吗?