如何复制具有常量字段的成员

How to copy members with const fields

本文关键字:常量 字段 成员 何复制 复制      更新时间:2023-10-16

我发现这个代码有一个问题:

struct Example
{
    const int k;
    Example(int k) : k(k) {}
};
struct Board
{
    Example table[4];
    Board() {} // ???
};

我的问题是如何初始化表变量。如果我提供一个默认的构造函数,我将无法更改这个常量字段。有变通办法吗?我也不能依赖复制构造函数。

你是指以下内容吗?

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

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

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