Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a 2x2 matrix in a class default constructor

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?

like image 408
Jon Avatar asked Sep 04 '26 03:09

Jon


2 Answers

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.

like image 139
Sergey Kalinichenko Avatar answered Sep 06 '26 17:09

Sergey Kalinichenko


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;
}
like image 21
Mike Seymour Avatar answered Sep 06 '26 18:09

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!