How to copy elements with constant fields

I found a problem with this code:

struct Example
{
    const int k;
    Example(int k) : k(k) {}
};

struct Board
{
    Example table[4];
    Board() {} // ???
};

      

My question is how to initialize a table variable. If I provide a default constructor, I cannot change this const field. Is there a workaround? I also cannot rely on the copy constructor.

+3


source to share


2 answers


Do you mean the following?

#include <iostream>

int main()
{
    struct Example
    {
        const int k;
        Example(int k) : k(k) {}
    };

    struct Board
    {
        Example table[4];
        Board() : table { 1, 2, 3, 4 } {} // ???
    };

    Board b;

    for ( const auto &e : b.table ) std::cout << e.k << ' ';
    std::cout << std::endl;
}

      



Another approach is to define the table as a static data member, provided that it will be initialized the same for all objects of the class. for example

struct Example
{
    const int k;
    Example(int k) : k(k) {}
};

struct Board
{
    static Example table[4];
    Board() {} // ???
};

Example Board::table[4] = { 1, 2, 3, 4 };

      

+4


source


Directly initialize each element in the array with a constructor: Board(): table{9, 8, 7, 6} {}



0


source







All Articles