Pass an object to a class constructor

僤鯓⒐⒋嵵緔 提交于 2019-12-10 19:33:41

问题


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:


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.



来源:https://stackoverflow.com/questions/23183523/pass-an-object-to-a-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!