hw12_04.cpp

4、设计一个名为PolyInt的类,表示整系数多项式(即系数为整数),这个类包括:
 两个私有型数据成员:
一个int型整数: int n, 表示多项式的次数,
一个int型指针: int *a, 表示多项式的系数,即𝑝𝑝
𝑥
𝑥 =𝑎𝑎0+𝑎𝑎1𝑥𝑥+𝑎𝑎2𝑥𝑥2+⋯+𝑎𝑎𝑛𝑛𝑥𝑥𝑛𝑛
其中a指向系数向量[𝑎𝑎0, 𝑎𝑎1, 𝑎𝑎2, ⋯ , 𝑎𝑎𝑛𝑛]的首地址
 一个不带形参的构造函数, 用于创建0多项式𝑝𝑝
𝑥
𝑥 =0, 即 n=0, a[0]=0
 一个带形参的构造函数: PolyInt(int n, int a[]) (提示: 在构造函数中用new为对象申请存储空间)
 成员函数void Display(), 按数组方式输出多项式,如 𝑝𝑝
𝑥
𝑥 =1+2𝑥𝑥+4𝑥𝑥3 输出为[1,2,0,4]
 使用非成员函数方式实现两个整系数多项式的加法运算:
PolyInt operator+(const PolyInt & p, const PolyInt & q)
 析构函数:~PolyInt(),释放构造函数中由new申请的存储空间。
实现这个类,并在主函数中测试这个类:创建多项式𝑝𝑝
𝑞
𝑞
𝑥
𝑥 =1+2𝑥𝑥+4𝑥𝑥3 和


𝑥 =2+4𝑥𝑥2+3𝑥𝑥3+5𝑥𝑥5,计算s(x)=p(x)+q(x),并输出p(x), q(x) 和 s(x)。
#include <iostream>

using namespace std;

class PolyInt {
public:
    PolyInt() : n(0), a(nullptr) {}
    PolyInt(const int n, const int a[]) {
        this->n = n;
        this->a = new int[n];
        for (int i = 0; i < n; ++i) {
            this->a[i] = a[i];
        }
    }

    ~PolyInt() {
        delete[] a;
    }
    void Display() const {
        cout << "[";
        for (int i = 0; i < n; i++) {
            cout << a[i];
            if (i < n - 1) {
                cout << ",";
            }
        }
        cout << "]" << endl;
    }
    friend PolyInt operator+(const PolyInt &p, const PolyInt &q);
private:
    int n;
    int *a;
};
PolyInt operator+(const PolyInt &p, const PolyInt &q) {
    int newn = max(p.n, q.n);
    int *newa = new int[newn];
    for (int i = 0; i < newn; ++i) {
        if (i < p.n && i < q.n) {
            newa[i] = p.a[i] + q.a[i];
        } else if (i < p.n) {
            newa[i] = p.a[i];
        } else {
            newa[i] = q.a[i];
        }
    }
    return PolyInt(newn, newa);
}
int main() {
    int p[] = {1, 2, 0, 4};
    int q[] = {2, 0, 4, 3, 5};
    PolyInt p1(4, p);
    PolyInt q1(5, q);
    PolyInt s = p1+q1;
    cout << "p(x): ";
    p1.Display();
    cout << "q(x): ";
    q1.Display();
    cout << "s(x): ";
    s.Display();
    return 0;
}

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部