将一个类对象的指针分配给另一个类的对象c++

Assign the pointer of one class object to another class object c++

本文关键字:对象 分配 另一个 c++ 指针 一个      更新时间:2023-10-16

所以我对C++编程很陌生,所以如果我问了一些琐碎的问题,我会事先道歉。我的任务是对多项式进行加法、乘法和求值,其中指定多项式的每个项都由一个具有私有变量的Node类表示:double coefficient、int power和Node*next。

class Node{
private:
double coef;
int power;
Node *next;
public: blah
}

该链表的头(对于每个多项式)将存储在Poly对象的数组中,其中我的Poly类中唯一的私有变量是Node*head。

class Poly{
private:
Node *head;
public:poly functions;
}

用户要通过从我的多项式数组中选择一个元素来选择他们想要使用的多项式,这将为所选多项式提供头部。

poly_array[n];

然而,我现在的问题是,这个数组的元素是对象Poly的,我想让它成为Node类,这样我就可以实际提取它在类中的内容,并使用这种方法遍历所选多项式的节点。这是我试图实现的代码,但我对convert poly的函数调用返回了垃圾。我不知道下一步该尝试什么方法。提前谢谢。这就是我试图首先遍历多项式以显示其内容的地方。

void init_polydisplay(vector<Poly*> polynomial_array, int numofpolys)
{
Poly *polyobject;
Node *polyhead;
for (int n = 0; n < numofpolys; n++)
{
    temp3.getnodehead();
    polyhead=polyobject->convertPoly(polynomial_array[n]);
}
}

我试图返回Node*,而不是仅仅返回多项式的头。

Node* Poly::convertPoly(Poly* tmp)
{
return (Node *) tmp;
}

您可以在Poly 中定义get_head()函数

class Poly{
private:
Node *head;
public:
 Node * get_head()
    {
      return head;
    }
};

并以这种方式使用:

polyhead = polynomial_array[n]->get_head();