Загрузка данных
#include <iostream>
using namespace std;
// Базовый класс (полином 2 степени)
class Polynomial2 {
protected:
double* coef; // указатель на массив коэффициентов
public:
// Конструктор без параметров
Polynomial2() {
coef = new double[3]; // 3 коэффициента
for (int i = 0; i < 3; i++)
coef[i] = 0;
}
// Конструктор с параметрами
Polynomial2(double a0, double a1, double a2) {
coef = new double[3];
coef[0] = a0;
coef[1] = a1;
coef[2] = a2;
}
// Конструктор копирования
Polynomial2(const Polynomial2& other) {
coef = new double[3];
for (int i = 0; i < 3; i++)
coef[i] = other.coef[i];
}
// Деструктор
~Polynomial2() {
delete[] coef;
}
// Оператор присваивания
Polynomial2& operator=(const Polynomial2& other) {
if (this != &other) {
for (int i = 0; i < 3; i++)
coef[i] = other.coef[i];
}
return *this;
}
// Сумма коэффициентов
double sum() const {
return coef[0] + coef[1] + coef[2];
}
// Вывод
virtual void print() const {
cout << coef[2] << "x^2 + "
<< coef[1] << "x + "
<< coef[0] << endl;
}
// Оператор []
double& operator[](int index) {
return coef[index];
}
const double& operator[](int index) const {
return coef[index];
}
// Оператор +
Polynomial2 operator+(const Polynomial2& other) const {
return Polynomial2(
coef[0] + other.coef[0],
coef[1] + other.coef[1],
coef[2] + other.coef[2]
);
}
};
// Производный класс (полином 3 степени)
class Polynomial3 : public Polynomial2 {
public:
// Конструктор без параметров
Polynomial3() {
delete[] coef;
coef = new double[4];
for (int i = 0; i < 4; i++)
coef[i] = 0;
}
// Конструктор с параметрами
Polynomial3(double a0, double a1, double a2, double a3) {
coef = new double[4];
coef[0] = a0;
coef[1] = a1;
coef[2] = a2;
coef[3] = a3;
}
// Конструктор копирования
Polynomial3(const Polynomial3& other) {
coef = new double[4];
for (int i = 0; i < 4; i++)
coef[i] = other.coef[i];
}
// Деструктор
~Polynomial3() {
delete[] coef;
}
// Оператор присваивания
Polynomial3& operator=(const Polynomial3& other) {
if (this != &other) {
for (int i = 0; i < 4; i++)
coef[i] = other.coef[i];
}
return *this;
}
// Сумма коэффициентов
double sum() const {
return coef[0] + coef[1] + coef[2] + coef[3];
}
// Переопределение print
void print() const override {
cout << coef[3] << "x^3 + "
<< coef[2] << "x^2 + "
<< coef[1] << "x + "
<< coef[0] << endl;
}
// Оператор []
double& operator[](int index) {
return coef[index];
}
const double& operator[](int index) const {
return coef[index];
}
// Оператор +
Polynomial3 operator+(const Polynomial3& other) const {
return Polynomial3(
coef[0] + other.coef[0],
coef[1] + other.coef[1],
coef[2] + other.coef[2],
coef[3] + other.coef[3]
);
}
};
// Тестовая программа
int main() {
Polynomial3 p1(1, 2, 3, 4);
Polynomial3 p2(5, 6, 7, 8);
Polynomial3 p3 = p1 + p2;
p1.print();
p2.print();
p3.print();
cout << "Sum p3 = " << p3.sum() << endl;
p3[0] = 100;
p3.print();
return 0;
}