#include <iostream> using namespace std; int main() { int n1, n2; cin >> n1 >> n2; double a1[n1], a2[n2]; for(int i=0; i<n1; i++) cin >> a1[i]; for(int i=0; i<n2; i++) cin >> a2[i]; Polynomial p1(a1, n1); Polynomial p2(a2, n2); Polynomial pp; pp += p1; cout << pp << endl; p2 += pp; cout << p2 << endl; return 0; } /* 请在这里填写答案,你只需要完成复合赋值(+=)运算符函数即可,其他均已由系统实现 */
时间: 2023-06-19 19:03:10 浏览: 83
使用include <iostream>时一定要加using namespace std
以下是复合赋值运算符函数的实现:
```c++
Polynomial& operator+=(const Polynomial& other) {
int newDegree = max(degree, other.degree);
double* newCoeffs = new double[newDegree + 1];
for (int i = 0; i <= newDegree; i++) {
double sum = 0.0;
if (i <= degree) sum += coeffs[i];
if (i <= other.degree) sum += other.coeffs[i];
newCoeffs[i] = sum;
}
delete[] coeffs;
coeffs = newCoeffs;
degree = newDegree;
return *this;
}
```
该函数首先计算两个多项式的最高次数,然后动态分配一个新的系数数组,遍历新的系数数组,对于每一个次数,计算两个多项式在该次数的系数之和。最后释放原来的系数数组,将指针指向新的系数数组,并更新多项式的最高次数。最后返回该对象的引用,以支持链式运算。
阅读全文