如何复制具有 const 字段的成员

How to copy members with const fields

我发现这段代码有问题:

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

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

我的问题是如何初始化 table 变量。如果我提供默认构造函数,我将无法更改此常量字段。有解决方法吗?我也不能依赖复制构造函数。

你是指以下吗?

#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;
}

另一种方法是将 table 定义为静态数据成员,前提是它将对 class 的所有对象以相同的方式初始化。例如

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 };

直接用构造函数初始化数组中的每个元素:Board(): table{9, 8, 7, 6} {}