今回は、要素にアクセスするための関数呼び出し演算子と算術単項演算子を実装してみる。
// matrix.cpp #include <iostream> #include <initializer_list> template <typename T, int N> class Matrix { static_assert(N > 0, ""); public: //------------------------------------------ // // 挿入演算子 // //------------------------------------------ friend std::ostream& operator <<(std::ostream& os, const Matrix& x) { os << "["; for (int iRow = 0; iRow < N; iRow++) { os << "["; for (int iColumn = 0; iColumn < N; iColumn++) { os << x.elements_[iRow][iColumn]; if (iColumn != N - 1) os << ","; } os << "]"; if (iRow != N - 1) os << ","; } os << "]"; return os; } public: //------------------------------------------ // // コンストラクタ、デストラクタ、コピー、ムーブ // //------------------------------------------ Matrix() noexcept(noexcept(T())) {} Matrix(const T& a) { for (int i = 0; i < N; i++) elements_[i][i] = a; } Matrix(std::initializer_list<std::initializer_list<T>> ll) { auto itRow = ll.begin(); for (int iRow = 0; iRow < N && itRow != ll.end(); iRow++, ++itRow) { auto l = *itRow; auto itColumn = l.begin(); for (int iColumn = 0; iColumn < N && itColumn != l.end(); iColumn++, ++itColumn) { elements_[iRow][iColumn] = *itColumn; } } } Matrix(const Matrix&) noexcept = default; Matrix(Matrix&&) noexcept = default; ~Matrix() = default; Matrix& operator =(const Matrix&) & noexcept = default; Matrix& operator =(Matrix&&) & noexcept = default; Matrix&& operator =(const Matrix&) && noexcept = delete; Matrix&& operator =(Matrix&&) && noexcept = delete; public: //------------------------------------------ // // 要素の参照 // //------------------------------------------ T& operator ()(int row, int column) { return elements_[row][column]; } const T& operator ()(int row, int column) const { return elements_[row][column]; } public: //------------------------------------------ // // 算術単項演算子 // //------------------------------------------ Matrix operator +() const { return Matrix(*this); } Matrix operator -() const { Matrix ret; for (int iRow = 0; iRow < N; iRow++) { for (int iColumn = 0; iColumn < N; iColumn++) { ret.elements_[iRow][iColumn] = -elements_[iRow][iColumn]; } } return ret; } protected: T elements_[N][N] = {}; }; // class Matrix int main() { const Matrix<int, 3> x{{1,2,3},{4,5,6},{7,8,9}}; //x(1, 2) = 13; std::cout << x(1, 2) << std::endl; std::cout << -x << std::endl; return 0; }
実行結果は
6
[[-1,-2,-3],[-4,-5,-6],[-7,-8,-9]]
のようになる。
次回は、算術二項演算子、論理演算子を定義してみたい。
0 件のコメント:
コメントを投稿