[英]Pass an object to a class constructor
I have two classes: poly and Node. 我有两个类:poly和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.
我创建一个链接的节点列表,然后我想创建一个新的多边形对象,其中包含指向我的第一个Node对象的指针。
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 *. 我已经测试了我的代码,并确认“head”包含节点的链接列表,head也被声明为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. 我不明白为什么我不能将Node *传递给我的poly构造函数。
I don't understand why I can't pass a Node * to my poly constructor!!
我不明白为什么我不能将Node *传递给我的poly构造函数!
Because poly
needs to know that Node
is a type. 因为
poly
需要知道Node
是一种类型。 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. 或者,您可以在
poly
的定义之前放置Node
类定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.