C++递归地在类构造函数中创建对象

C++ create objects in the class constructor recursively

本文关键字:构造函数 创建对象 递归 C++      更新时间:2023-10-16

嗨,我正在做作业,我这里有一个问题。
我有一个类,定义是:

class WebNode
{
private:
char* m_webAddress;
char* m_anchorText;
WebNode** m_hyperlink;
int m_numOfHyperlinks;
public:
// CONSTRUCTOR member function
WebNode(const char* webAddress, const char* anchorText, int height);
// DESTRUCTOR member function
~WebNode();
// ACCESSOR member functions
// not important
};

我正在研究构造函数:WebNode::WebNode(const char* webAddress, const char* anchorText, int height) {}.构造函数应首先基于构造函数参数设置私有成员,然后应根据超链接递归创建新的WebNode对象。但我不能这样做,因为如果我在构造函数中使用new WebNode它会说no matching constructor for initialisation of WebNode.
那么如何在构造函数中创建新对象呢?

无论是在构造函数中还是在其他地方创建对象,都需要一个匹配的构造函数来进行调用。当您尝试通过以下方式创建对象时

new WebNode();

然后Webnode需要一个默认构造函数(即可以在没有参数的情况下调用的构造函数(。

class WebNode
{
private:
char* m_webAddress;
char* m_anchorText;
WebNode** m_hyperlink;
int m_numOfHyperlinks;
public:
WebNode(const char* webAddress, const char* anchorText, int height);
WebNode();   // <-----------
~WebNode();
};

我不能修改类定义,还有其他方法吗?

构造实例时传递参数:

new WebNode(some_web_address,some_anchor_text,h);