Pass an object to a class constructor

2019-07-13 14:02发布

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.

1条回答
太酷不给撩
2楼-- · 2019-07-13 14:15

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.

查看更多
登录 后发表回答