首页 > 解决方案 > 我应该如何编写这个复制构造函数?

问题描述

我有班级模型:

class model
{
private:
    link_list list;
    float parameter_B1;
    float parameter_B0;
public:
    model();
    float getparameter_B1() const;
    float getparameter_B0() const;
    float predict();
    void info();
};

正如你所看到的,它有一个 link_list 属性,它是:

class link_list
{
private:
    node* head;
public:

    link_list();
    link_list insertNewNode(Pair _pairs);
    Pair average();
    float parameters1(Pair _average);
    float parameters2(Pair _average, float par1);
    float error(float para1,float para2);
    ~link_list();
    link_list(const link_list& p)
    {

            /*head = new node;
            head->setpair(p.head->getpair());
            head->setnextnode(p.head->getnextnode());*/

    };
};

我必须从我的函数中返回对象(本身)insertNewNode并使用复制构造函数将新节点添加到我的列表中。

我是 C++ 的新手,但是我读过一些关于当我们有动态数据时需要定义复制构造函数的内容,因为默认的复制构造函数只复制原始数据成员的地址。

但我不知道如何编写我的复制构造函数?

我试过这个:

    link_list(const link_list& p)
    {

            head = new node;
            head->setpair(p.head->getpair());
            head->setnextnode(p.head->getnextnode());

    };

但它只适用于我的第一个节点,对于其他节点,我会遇到分段错误。这是我的班级节点:

struct Pair
{
float x;
float y;
};
class node
{
private:
    Pair _pair;
    node* next;
public:
    node() {};
    void setpair(Pair p);
    Pair getpair() const;
    node* getnextnode() const;
    void setnextnode(node* temp);
};

这是模型构造函数,我在这里调用我的函数insertNewNode

model::model()
{
    char filename[300];
    cout << "enter file name(path\\filname.txt):" << endl;
    cin >> filename;
    FILE* fp;
    fp = fopen(filename, "r+");
    float x, y;
    if (fp == NULL)
    {
        cout << "Unable to open the file!" << endl;
        exit(EXIT_FAILURE);
    }
    else
    {
        while (!feof(fp))
        {
            if (fscanf(fp, "%f\t%f", &x, &y) == 2)
            {
                Pair p(x, y);
                list.insertNewNode(p);

            }
        }
    }
    Pair _average = list.average();
    parameter_B1 = list.parameters1(_average);
    parameter_B0 = list.parameters2(_average, parameter_B1);
}

这是我的insertNewNode

link_list link_list::insertNewNode(Pair _pairs)
{
    node* temp;
    temp = new node;
    temp->getpair().set_counter();
    /*temp->setpair(_pairs);
    temp->setnextnode(head);
    head = temp;*/
    temp->setpair(_pairs);
    temp->setnextnode(NULL);
    if (head == NULL)
    {
        head = temp;
        return *this;
    }
    node* tmp = head;
    while (tmp->getnextnode() != NULL)
        tmp = tmp->getnextnode();
    tmp->setnextnode(temp);
    return *this;
}

最后这是我的析构函数:

link_list::~link_list()
{
    node* current = head;
    node* next;

    while (current != NULL)
    {
        next = current->getnextnode();
        delete(current);
        current = next;
    }
    head = NULL;
}

PS:pair是一个类,如果也包含它,我的问题会变得很长。我只想知道这种复制构造函数的想法,假设数据是任何东西并且有链表类用作另一个类的属性。

在此先感谢您的帮助,并很抱歉提出很长的问题。

标签: c++dynamicdynamic-memory-allocationcopy-constructor

解决方案


推荐阅读