How do implement a class that displays a 2 by 2 matrix

Dani AI

Generated

Building on 's storage hint and 's comment about visibility, a small class that focuses on three things is the simplest and most maintainable approach: compact private storage, safe indexed access, and a single standard way to print. For a fixed 2x2 matrix prefer value semantics (no heap), light-weight accessors, and a free stream operator so the matrix prints like any other C++ object.

Here is a minimal example showing those ideas (contiguous storage, accessor, and stream output):

#include <array>
#include <iostream>

class Matrix2x2 {
    std::array<double,4> data_;
public:
    Matrix2x2(double a00=0, double a01=0, double a10=0, double a11=0) noexcept
      : data_{a00,a01,a10,a11} {}

    double& operator()(size_t r, size_t c) noexcept { return data_[r*2 + c]; }
    double  operator()(size_t r, size_t c) const noexcept { return data_[r*2 + c]; }

    friend std::ostream& operator<<(std::ostream& os, const Matrix2x2& m) {
        os << '[' << m(0,0) << ' ' << m(0,1) << "]\n"
           << '[' << m(1,0) << ' ' << m(1,1) << ']';
        return os;
    }
};

Notes and quick tips: keep index checks in debug builds only (asserts) to avoid release overhead; prefer std::array for small fixed-size storage (std::array); implement only what you need (printing, transpose, multiply) and rely on the Rule of Zero for copy/move. For printing using streams, a free operator<< matches standard idioms (operator<< reference).

Recommended Answers

All 2 Replies

struct matrix_2x2
{
  //interesting functions here
  double v[2][2];  
};

?

Well ifezuec, if you are wondering whats a struct...its just like a class with everything (data members as well as member functions) public by default.
If you wanted strictly a class you can simply replace the "struct" with "class" but in that case your 2d matrix will no longer be public by default.

Hope it helps.


P.S: Daniweb has a policy that we shouldn't be giving out codes till you show some good efforts. The hint by Aranarth is, I think, enough for you to start.
Good luck...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.