问题
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