Home > OS >  The definition of struct in C
The definition of struct in C

Time:05-12

I am confused about the following definition of the struct.

struct Matrix{
    int a, b;
    Matrix(int a =0, b = 0): a(a), b(b){} 
} m[26];

What does the statement "Matrix(int a =0, b = 0): a(a), b(b){} " mean and why we need it? Does "m[26]" means we define an array of Matrix?

CodePudding user response:

The m[26] says to create an array of 26 of the struct Matrix type. That is fine in C.

However, the Matrix(int a=0, b==0): a(a), b(b) {} is specifying a constructor which assigns a and b parameters to a and b member variables in the struct Matrix is c .

CodePudding user response:

Matrix(int a = 0, b = 0) :
    a(a), b(b)
{
}

is a constructor with two parameters, a and b. They have default values, each being 0.

It initializes its member variables a and b with the provided arguments.

You can use it for example like this:

Matrix m1;         // initializes a and b with 0 each
Matrix m2(23);     //  initializes a and b with 23 and 0, respectively
Matrix m3(23, 42); //  initializes a and b with 23 and 42, respectively
  • Related