将对象传递给类构造函数 [英] Pass an object to a class constructor

查看:94
本文介绍了将对象传递给类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类:poly和Node。我创建了一个节点的链接列表,然后我想创建一个新的多边形对象,其中包含指向我的第一个Node对象的指针。

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.

这里是调用代码:

poly *polyObj = new poly(head);

我已经测试了我的代码,并确认 head包含节点的链接列表,head也为声明为节点*。

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

以下是类定义:

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;
    }
};

我不明白为什么不能将Node *传递给多边形构造函数。

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!!

因为 poly 需要知道 Node 是一种类型。您可以通过前向声明来实现:

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;
  }
};

或者,您可以放置​​ Node poly 定义之前的定义。

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

这篇关于将对象传递给类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆