[英]c++ extend constructor of same class (no inheritance)
我可能在這里的某個地方找到了我的答案,但不過,我想確定一下。
我正在制作圖形中表示的東西(因此是節點),我想知道構造函數的這個代碼是否按照我的想法運行。
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 ++ 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-initializer列表中唯一的初始化程序。
考慮到將構造函數聲明為此構造函數的方法沒有多大意義
Node(Node*const& parent_p);
聲明它就更有道理了
Node( const Node *parent_p );
否則,看起來parent_p指向的節點可以在構造函數內部更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.