一个类有且只有一个析构函数。若用户没有显式定义,系统会自动生成默认的析构函数。
#include <iostream>
#include <vector>
#include <stdexcept>
#include <iomanip>
template <typename T>
class Matrix
{
public:
typedef T value_type;
typedef std::size_t size_type;
Matrix(size_type rows, size_type cols) : _data(rows * cols), _rows(rows), _cols(cols)
{
if (rows == 0 || cols == 0)
throw std::invalid_argument("invalid rows or cols");
}
Matrix(const Matrix &other) : _data(other._data), _rows(other._rows), _cols(other._cols) {}
Matrix(Matrix &&other) : _data(std::move(other._data)), _rows(other._rows), _cols(other._cols)
{
other._rows = 0;
other._cols = 0;
}
Matrix(const std::initializer_list<std::initializer_list<T>> &list)
: Matrix(list.size(), list.size() ? list.begin()->size() : 0)
{
size_type i = 0, j = 0;
for (const auto &l : list)
{
for (const auto &v : l)
{
(*this)(i, j) = v;
j++;
}
j = 0;
i++;
}
}
~Matrix() {}
Matrix &operator=(const Matrix &other)
{
if (this != other)
{
_data = other._data;
_rows = other._rows;
_cols = other._cols;
}
return *this;
}
Matrix &operator=(Matrix &&other)
{
_data = std::move(other._data);
_rows = other._rows;
_cols = other._cols;
other._rows = 0;
other._cols = 0;
return *this;
}
size_type rows() const { return _rows; }
size_type cols() const { return _cols; }
value_type operator()(size_type i, size_type j) const
{
if (i >= _rows || j >= _cols)
throw std::invalid_argument("invalid index");
return _data[i * _cols + j];
}
value_type &operator()(size_type i, size_type j)
{
if (i >= _rows || j >= _cols)
throw std::invalid_argument("invalid index");
return _data[i * _cols + j];
}
private:
std::vector<value_type> _data;
size_type _rows;
size_type _cols;
};
template <typename T>
std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix)
{
typedef typename Matrix<T>::size_type size_type;
for (size_type i = 0; i < matrix.rows(); i++)
{
os << "[";
for (size_type j = 0; j < matrix.cols(); j++)
os << std::setw(3) << matrix(i, j) << ' ';
os << "]\n";
}
return os;
}
int main()
{
Matrix<int> m = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}};
std::cout << m;
return 0;
}