如何复制具有常量字段的成员
How to copy members with const fields
我发现这个代码有一个问题:
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} {}
相关文章:
- 将结构字段的类型展开为可变模板参数
- 将位字段导出到数组
- 为了方便起见,我应该避免公开私有字段变量吗
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在java中读取c++字节的位字段
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 私有字段对象与私有继承?
- 声明没有默认构造函数的字段
- C++内存模型和位字段的最大序列
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- C++ win32 如何使密码字段可选并启用复制和粘贴?
- 在 C++20 之前,在带有常量或引用字段的"A"上调用 'std::vector<A>
- 列出常量和数组结构字段的初始化
- c++ 11统一初始化:字段初始化不是常量
- 为什么常量 POD 对象中的字段本身不是常量?
- 如何复制具有常量字段的成员
- 为什么这可以让我获得一个指向常量对象字段的非常量指针
- 有没有办法强制Protocol Buffer使用常量字段大小
- C++11 MinGW 4.9.1 shared_ptr和常量静态类字段结果"Undefined reference"