简体   繁体   中英

C++ create objects in the class constructor recursively

Hi I'm working on my homework and I have a problem here.
I have a class and definition is:

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
};

And I'm working on the constructor: WebNode::WebNode(const char* webAddress, const char* anchorText, int height) {} . The constructor should firstly setup the private member based on the constructor parameter, then it should recursively create new WebNode objects depending on hyperlinks. But I cannot do that because if I use new WebNode in the constructor it will say no matching constructor for initialisation of WebNode .
So how can I create new objects in the constructor?

Whether you create object in the constructor or elsewhere, you need a matching constructor for the call. When you attempt to create an object via

new WebNode();

then Webnode needs a default-constructor (ie one that can be called without parameters).

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();
};

I'm not allowed to modify the class definition, is there other ways?

Pass the parameters when constructing instances:

new WebNode(some_web_address,some_anchor_text,h);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM