Начал изучать C++. Прочитал статью закреплённую. Хелловорлд и прочие мелкие поделки компилируются нормально. Сейчас нужно, чтобы класс и демонстрационная программа были в разных файлах. Попытка скомпилировать файл с классом не приводит к желаемому результату.
Текст:
#include <iostream>
#include <cmath>
#include <new>
/* Класс для работы с квадратными матрицами */
class matrix
{
int order, **coefficents_set;
static bool indication;
public:
matrix (); // Конструктор по умолчанию
matrix (const matrix &copied_object); // Конструктор копирования
matrix (int n); // Перегруженный конструктор для создания матриц заранее заданного размера
~matrix (); // Деструктор
bool get_object_memory (); // Выделение динамической памяти квадратной матрице
int determinant_calculation (); // Расчёт определителя
matrix *transposition (); // Транспонирование матрицы
static bool condition (); // Проверка состояния матриц (возникновения ошибок)
void init (); // Ручной ввод элементов матрицы
void output (); // Вывод матрицы
void put_element (int j, int i, int n); // Добавление или переписывание одного коэффицента
}
static bool matrix::indication;
/* Конструктор класса matrix по умолчанию */
matrix::matrix ()
{
cout << "Введите порядок квадратной матрицы" << endl;
cin >> order;
coefficents_set = NULL;
}
/* Конструктор копирования класса matrix */
matrix::matrix (const matrix &copied_object)
{
order = copied_object.order;
get_object_memory ();
for (int i = 0; i <= order - 1; i++)
for (int j = 0; j <= order - 1; j++)
coefficents_set [i] [j] = copied_object.coefficents_set [i] [j];
}
/* Перегруженный конструктор класса matrix - для создания матриц с заранее заданным порядком */
matrix::matrix (int n)
{
order = n;
coefficents_set = NULL;
}
/* Деструктор класса matrix */
matrix::~matrix ()
{
if (coefficents_set != NULL)
{
for (int i = 0; (i <= order - 1) && (coefficents_set != NULL); i++)
delete coefficents_set [i];
delete coefficents_set;
}
}
/* Выделение динамической памяти квадратной матрице */
bool matrix::get_object_memory ()
{
if (order >= 1)
{
try
{
coefficents_set = new int * [order];
} catch (bad_alloc xa)
{
indication = true;
coefficents_set = NULL;
cout << "Ошибка при выделении памяти (строки)." << endl;
}
for (int i = 0; (i <= order - 1) && (!indication); i++)
{
try
{
coefficents_set [i] = new int [order];
} catch (bad_alloc xa)
{
indication = true;
coefficents_set [i] = NULL;
cout << "Ошибка при выделении памяти (столбцы)." << endl;
}
}
}
else
{
cout << "Недопустимое значение порядка." << endl;
indication = true;
}
if (indication)
cout << "Аварийное завершение программы." << endl;
else
{
cout << "Память успешно выделена." << endl;
}
return indication;
}
/* Расчёт определителя */
int matrix::determinant_calculation ()
{
int determinant = 0;
if (order == 1)
determinant = coefficents_set [0] [0];
else if (order == 2)
determinant = coefficents_set [0] [0] * coefficents_set [1] [1] - coefficents_set [0] [1] * coefficents_set [1] [0];
else
for (int i = 0, j = 0; j <= order - 1; j++)
{
matrix minor (order - 1);
minor.get_object_memory ();
if (!(condition () ) )
{
for (int m = 0, x = 0; (m <= order - 1) && (x <= order - 2); m++)
if (m != i)
{
for (int n = 0, y = 0; (n <= order - 1) && (y <= order - 2); n++)
if (n != j)
{
minor.put_element (x, y, coefficents_set [m] [n] );
y++;
}
x++;
}
determinant += coefficents_set [i] [j] * ( (int)pow ( (double)(-1), i + j) ) * minor.determinant_calculation ();
}
}
return determinant;
}
/* Транспонирование матрицы */
matrix *matrix::transposition ()
{
matrix *transposed_matrix;
try
{
transposed_matrix = new matrix;
} catch (bad_alloc xa)
{
cout << "Ошибка при выделении памяти (транспонирование)" << endl;
transposed_matrix = NULL;
}
if (transposed_matrix != NULL)
{
transposed_matrix -> get_object_memory ();
if (!(condition () ) )
for (int i = 0; i <= order - 1; i++)
for (int j = 0; j <= order - 1; j++)
transposed_matrix -> put_element (j, i, coefficents_set [i] [j]);
else
transposed_matrix = NULL;
}
return transposed_matrix;
}
/* Информация о возникновении ошибок */
bool matrix::condition ()
{
return indication;
}
/* Ручной ввод элементов матрицы */
void matrix::init ()
{
for (int i = 0; i <= order - 1; i++)
for (int j = 0; j <= order - 1; j++)
{
cout << "Введите элемент [" << i + 1 << "] [" << j + 1 << "]: ";
cin >> coefficents_set [i] [j];
}
cout << "Матрица успешно создана." << endl;
}
/* Вывод матрицы */
void matrix::output ()
{
setf (ios::left);
unsetf (ios::right);
width (3);
for (int i; i <= order - 1; i++)
{
cout << "|";
for (int j; j <= order - 1; j++)
cout << coefficents_set [i] [j];
cout << "|" << endl;
}
}
/* Добавление или переписывание одного коэффицента */
void matrix::put_element (int j, int i, int n)
{
coefficents_set [j] [i] = n;
}
Для компиляции использую следующую команду:
g++ -c -o class.o class.cpp
Вывод компилятора:
class.cpp:30:21: error: two or more data types in declaration of ‘indication’
class.cpp: In constructor ‘matrix::matrix()’:
class.cpp:35:2: error: ‘cout’ was not declared in this scope
class.cpp:35:81: error: ‘endl’ was not declared in this scope
class.cpp:36:2: error: ‘cin’ was not declared in this scope
class.cpp: In member function ‘bool matrix::get_object_memory()’:
class.cpp:79:12: error: expected type-specifier before ‘bad_alloc’
class.cpp:79:22: error: expected ‘)’ before ‘xa’
class.cpp:79:22: error: expected ‘{’ before ‘xa’
class.cpp:79:22: error: ‘xa’ was not declared in this scope
class.cpp:79:24: error: expected ‘;’ before ‘)’ token
class.cpp:91:14: error: expected type-specifier before ‘bad_alloc’
class.cpp:91:24: error: expected ‘)’ before ‘xa’
class.cpp:91:24: error: expected ‘{’ before ‘xa’
class.cpp:91:26: error: expected ‘;’ before ‘)’ token
class.cpp:101:3: error: ‘cout’ was not declared in this scope
class.cpp:101:74: error: ‘endl’ was not declared in this scope
class.cpp:106:3: error: ‘cout’ was not declared in this scope
class.cpp:106:76: error: ‘endl’ was not declared in this scope
class.cpp:109:3: error: ‘cout’ was not declared in this scope
class.cpp:109:62: error: ‘endl’ was not declared in this scope
class.cpp: In member function ‘matrix* matrix::transposition()’:
class.cpp:159:11: error: expected type-specifier before ‘bad_alloc’
class.cpp:159:21: error: expected ‘)’ before ‘xa’
class.cpp:159:21: error: expected ‘{’ before ‘xa’
class.cpp:159:21: error: ‘xa’ was not declared in this scope
class.cpp:159:23: error: expected ‘;’ before ‘)’ token
class.cpp: In member function ‘void matrix::init()’:
class.cpp:192:4: error: ‘cout’ was not declared in this scope
class.cpp:193:4: error: ‘cin’ was not declared in this scope
class.cpp:196:2: error: ‘cout’ was not declared in this scope
class.cpp:196:61: error: ‘endl’ was not declared in this scope
class.cpp: In member function ‘void matrix::output()’:
class.cpp:202:8: error: ‘ios’ has not been declared
class.cpp:202:17: error: ‘setf’ was not declared in this scope
class.cpp:203:10: error: ‘ios’ has not been declared
class.cpp:203:20: error: ‘unsetf’ was not declared in this scope
class.cpp:204:10: error: ‘width’ was not declared in this scope
class.cpp:208:3: error: ‘cout’ was not declared in this scope
class.cpp:213:18: error: ‘endl’ was not declared in this scope
Судя по выводу, если я правильно понял, почему-то не подключаются заголовки. Хотелось бы узнать, в чём проблема, и как её решить.