【问题标题】:Do I need to write anything in the destructor of this class? [duplicate]我需要在这个类的析构函数中写什么吗? [复制]
【发布时间】:2012-01-07 01:52:50
【问题描述】:

谢谢大家!现在我改变了我的逻辑。因为如果我包含指向自身的相同指针,它将创建无限循环。那么对于这个修改后的版本,我需要编写析构函数吗?

#include <stdio.h>
#include <stdlib.h>
#include <tr1/array>

using namespace std;
class Graphnode {

public:
    std::tr1::array<int, 16> state;
    int x;
    int depth;
    Graphnode(std::tr1::array<int, 16>,int,int);
    Graphnode();
    //~Graphnode();

};
Graphnode::Graphnode()
{
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = 0;
    }
    x = 0;
    depth = 0;
}
Graphnode::Graphnode(std::tr1::array<int, 16> _state,int _x,int _d)
{   
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = _state[i];
    }
    x = _x;
    depth = _d;
}
/*Graphnode::~Graphnode()
{
}*/

【问题讨论】:

  • 您在构造函数中得到无限递归,因为updownleftright 都在递归调用同一个构造函数。重新思考创建新Graphnodes 的方式的逻辑。
  • 也许我只是慢,但你所说的“自给自足”是什么意思?
  • 所以我们不应该在自身内部包含一个指针?
  • 我已经修改了我的代码。所以这不会创建递归调用。我想知道我应该在析构函数中写什么?由于现在没有指针,我还需要析构函数吗?
  • 既然你改变了问题的代码和正文,标题就完全关闭了......

标签: c++ constructor destructor


【解决方案1】:

当您尝试创建一个 Graphnode 时,您的代码将创建一个无限循环

您可以尝试为子 Graphnodes 创建一个特定的构造函数,以便在该构造函数中不会创建更多 Graphnode

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2014-04-24
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2020-11-15
    • 2015-08-07
    相关资源
    最近更新 更多