我可能在这里的某个地方找到了答案,但尽管如此,我想确定一下。
我正在制作在图形中表示的东西(因此是节点(,我想知道构造函数的这段代码是否按照我的想法工作。
G++不会抱怨。
我有以下课程:
#ifndef viper_node
#define viper_node
#include "../globals.hpp"
#include <vector>
/**
* @brief The base class for the nodes
*/
class Node {
public:
/**
* @brief base constructor for the node
*/
Node();
/**
* @brief exteded constructor for the node
* @param [in] parent_p the pointer to the parent of the new node
*/
Node(Node*const& parent_p);
/**
* @brief extended^2 constructor for the node
* @param [in] parent_p the pointer to the parent of the new node
* @param [in] name the name of the node
*/
Node(Node*const& p, std::string const& name);
/**
* @brief base destructor
*/
~Node();
protected:
/// pointer to the parent node of this one (nullptr if rootnode)
Node* parent;
///pointers to the children
std::vector<Node*> children;
///the name of the class/func/var (ex: children)
std::string name;
///description of the name/func/var (ex: pointers to the children)
std::string description;
///the properties of the node (static, private,...)
uint flags;
/// the type of the node (function, variable, binary, etc.)
nodeType node_type;
///the scope of the node (global, class member, function local)
nodeScope scope;
unsigned long get_id() {return id;};
private:
///the id of the node (unique)
unsigned long id;
///to keep track of the next unused id
static unsigned long maxID;
};
#endif
以及以下定义:
#include "node.hpp"
unsigned long Node::maxID = 0;
Node::Node()
{
parent = nullptr;
flags = 0;
id = maxID++;
}
Node::Node(Node*const& parent_p) : Node::Node()
{
parent = parent_p;
}
Node::Node(Node*const& p, std::string const& Name) : Node::Node(p)
{
name = Name;
}
Node::~Node()
{
parent = nullptr;
for (auto it : children)
{
delete it;
}
}
我的问题是这样的:
如果我调用Node(parent_p,"name")
,函数
Node(parent_p)
本身前面有Node()
吗?感谢您的帮助:-(
是的,您可以按照 C++11 标准。维基文章。
还有一个快速的实证验证:
using namespace std;
class A
{
public:
A()
{
cout << "Hello ";
}
A(int x) : A()
{
cout << "World!" << endl;
}
};
int main()
{
A a(1);
return 0;
}
指纹:
世界您好!
是的。
这就是在C++11(2011年完成的语言修订(中引入的"委派构造函数"。
是的,您可以委托给自(包括(C++11 以来的其他构造函数。
使用 C++03,您必须求助于其他方法,例如init
函数和人工虚拟基类。
C++11 还引入了构造函数的继承,并带有 using
声明,减少了常见简单情况的样板数量。
这是一个有趣的读物。
委托构造函数通常用于相反的方向,这可能会很有趣。
#include "node.hpp"
unsigned long Node::maxID = 0;
Node::Node():Node(nullptr)
{
}
Node::Node(Node*const& parent_p) : Node(parent_p, "")
{
}
Node::Node(Node*const& p, std::string const& Name)
{
parent = p;
name = Name;
flags = 0;
id = maxID++;
}
此外,这种特殊情况也可以使用默认参数轻松实现。
Node::Node(Node*p = 0, std::string const& Name = "")
{
parent = p;
name = Name;
flags = 0;
id = maxID++;
}
它们是所谓的委托构造函数。他们将类构造委托给其他构造函数。如果构造函数以这种方式使用,则它应该是 mem 初始值设定项列表中的唯一初始值设定项。
考虑到以这种构造函数的方式声明构造函数没有多大意义
Node(Node*const& parent_p);
简单地声明它更有意义
Node( const Node *parent_p );
否则,看起来parent_p指向的节点可以在构造函数中更改。