多項式類中 operator*(乘法)和 operator+= 運算運行失敗,疑似內存管理或邏輯錯誤。
// 原代碼缺陷
Polynomial *p = new Polynomial[num]; // 僅分配 Polynomial 對象數組
// p[i].p_coefs、p[i].p_exps 仍為野指針,p[i].num 未賦值
// 隨後直接訪問 p[i].p_coefs[j] → 未定義行為/崩潰
// 原代碼缺陷
Polynomial& operator+=(const Polynomial& x) {
return *this + x; // 返回臨時對象的引用 → 懸垂引用
}
Polynomial operator*(const Polynomial& x) const {
Polynomial *p = new Polynomial[num];
Polynomial sum; // 默認構造函數需確保指針初始化為 nullptr
for (int i = 0; i < num; i++) {
// 關鍵:為每個臨時多項式分配內部數組內存
p[i].p_coefs = new double[x.num];
p[i].p_exps = new int[x.num];
p[i].num = x.num; // 必須設置項數
for (int j = 0; j < x.num; j++) {
p[i].p_coefs[j] = p_coefs[i] * x.p_coefs[j];
p[i].p_exps[j] = p_exps[i] + x.p_exps[j];
}
}
for (int i = 0; i < num; i++) {
sum = sum + p[i]; // 依賴正確的 operator+
}
// 釋放臨時數組內存
for (int i = 0; i < num; i++) {
delete[] p[i].p_coefs;
delete[] p[i].p_exps;
}
delete[] p;
return sum;
}
// 正確實現:原地修改並返回 *this
Polynomial& operator+=(const Polynomial& x) {
*this = *this + x; // 調用 operator+ 得到結果,再賦值給自身
return *this;
}
// 同理修復 -= 和 *=
Polynomial& operator-=(const Polynomial& x) {
*this = *this - x;
return *this;
}
Polynomial& operator*=(const Polynomial& x) {
*this = *this * x;
return *this;
}
nullptr,num = 0,避免野指針。new Polynomial[n] 後,必須為每個元素的動態成員單獨分配內存。
4. 及時釋放:局部臨時數組用完後必須 delete[],防止內存洩漏。

修復後,多項式加、減、乘、+=、-=、*= 運算均正常工作,輸出結果符合預期。