Class 链接列表的复制构造函数不起作用

Copy Constructor for Class Linked List not working

我的复制构造函数引用了另一个地址而不是复制值,你们能帮我找到问题吗?

这是复制构造函数:

Poly::Poly(const Poly& copyList)
{

    // copy the first term
    power = copyList.power;
    coef = copyList.coef;

    if (copyList.nextTerm == NULL)
    {
        nextTerm = NULL;
    }
    else
    {
        // copy the next term
        PolyPtr trackCopy = copyList.nextTerm;
        nextTerm = new Poly;
        PolyPtr trackOriginal = nextTerm;
        PolyPtr newTerm;

        while (trackCopy != NULL)
        {
            newTerm = new Poly;
            newTerm->coef = trackCopy->coef;
            newTerm->power = trackCopy->power;
            trackOriginal->nextTerm = newTerm;
            trackOriginal = newTerm;

            trackCopy = trackCopy->nextTerm;

        }   
    }

}

这里的copyList是一个class,私有成员变量为coef、power和一个指向列表下一个节点的nextTerm

这是Poly的界面:

class Poly
{
    public:
        // constructors
        Poly();
        Poly(int constant);
        Poly(int coef, int power);
        Poly(const Poly& copyList);

        // set functions
        void setPower(int number);
        void setCoef(int number);
        void setNextTerm(Poly* link);

        // member function to compute
        int evaluate(int x);


    private:
        int power;
        int coef;
        Poly* nextTerm;

};
typedef Poly* PolyPtr;

这里有一个例子:

int main()
{
    PolyPtr polyNomial = new Poly(2, 3);
    PolyPtr nextTerm = new Poly(5, 8);

    polyNomial->setNextTerm(nextTerm);

    PolyPtr copyTerm(polyNomial);

    PolyPtr newTerm = new Poly(1, 2);
    copyTerm->setNextTerm(newTerm);

    cout << copyTerm->evaluate(3) << endl;

    cout << polyNomial->evaluate(3) << endl;


    return 0;
}

这里我预计 copyTerm 和 polyNomial 的计算是不同的,但它们是相同的

你的复制构造函数有一个错误。我添加了这个 friend 函数来显示链表和一个创建 Polys 并复制它们的小程序:

std::ostream& operator<<(std::ostream& os, const Poly& p) {
    const Poly* n = &p;
    os << '{';
    do {
        os << "addr:" << n << ' ' << n->power << ',' << n->coef << ' ';
        n = n->nextTerm;
    } while(n);
    return os << '}';
}

int main() {
    Poly p(1,2);
    p.setNextTerm(new Poly(3,4));

    std::cout << "orig: " << p << '\n'; // display the original
    Poly c(p);                          // copy construction
    std::cout << "copy: " << c << '\n'; // display the copy
}

注意副本中插入零的额外 Poly

orig: {addr:0x7ffcf2af8cd0 2,1 addr:0x1447eb0 4,3 }
copy: {addr:0x7ffcf2af8ce0 2,1 addr:0x1448ee0 0,0 addr:0x1448f00 4,3 }

如果像这样简化复制构造函数:

Poly::Poly(const Poly& rhs) : power(rhs.power), coef(rhs.coef), nextTerm(nullptr) {
    for(Poly *prev = this, *next = rhs.nextTerm; next; next = next->nextTerm) {
        prev->nextTerm = new Poly(next->coef, next->power);
        prev = prev->nextTerm;
    }
}

输出将是这样的:

orig: {addr:0x7ffdfe4b2eb0 2,1 addr:0x1f15eb0 4,3 }
copy: {addr:0x7ffdfe4b2ec0 2,1 addr:0x1f16ee0 4,3 }