简体   繁体   中英

Pass an object to a class constructor

I have two classes: poly and Node. I create a linked list of Nodes, then I want to create a new poly object that contains a pointer to my first Node object.

Here is the calling code:

poly *polyObj = new poly(head);

I have tested my code and confirmed that "head" contains the linked list of nodes, also head is declared as a Node *.

Here are the class definitions:

class poly
{
  private:
    Node *start;  
  public:
    poly(Node *head)
    {
      start = head;
    }
};

class Node
{
   private:
    double coeff;
    int exponent;
    Node *next;

  public:
    Node(double c, int e, Node *nodeobjectPtr)
    {
      coeff = c;
      exponent = e;
      next = nodeobjectPtr;
    }
};

I don't understand why I can't pass a Node * to my poly constructor.

I don't understand why I can't pass a Node * to my poly constructor!!

Because poly needs to know that Node is a type. You can achieve that via a forward declaration:

class Node; // fwd declaration

class poly
{
private:
    Node *start;    
public:
  poly(Node *head)
  {
    start = head;
  }
};

Alternatively, you can place the Node class definition before poly 's definition.

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