I'm trying to create a 2x2 matrix-class in C++ and want to initialize the matrix to an identity matrix through the default constructor. My class is:
class Matrix2x2
{
public:
Matrix2x2();
void setVal(int row, int col, double newVal);
private:
double n[2][2];
};
void Matrix2x2::setVal(int row, int col, double newVal)
{
n[row][col] = newVal;
}
I've tried a couple of different constructors, but none of them do what I want.
Matrix2x2::Matrix2x2(): setVal(0,0,1), setVal(0,1,0), setVal(1,0,0), setVal(1,1,1)
{ }
and
Matrix2x2::Matrix2x2(): n[0][0](1), n[0][1](0), n[1][0](0), n[1][1](1)
{ }
I realize that it's probably just a simple mistake somewhere, but I can't seem t find it, any ideas?
You can use an array aggregate:
class Matrix2x2 {
public:
Matrix2x2() : n({{3,1},{4,7}}) {
}
void setVal(int row, int col, double newVal);
private:
double n[2][2];
};
Demo on ideone.
In C++11:
Matrix2x2::Matrix2x2(): n{{1,0},{0,1}} {}
Historically, you could not initialise arrays in the initialiser list, so if you're stuck in the past then you'll have to assign the values in the constructor body:
Matrix2x2::Matrix2x2()
{
n[0][0] = 1; // or setVal(0,0,1) if you prefer
n[0][1] = 0;
n[1][0] = 0;
n[1][1] = 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With