![](/img/trans.png)
[英]How to copy (or swap) objects of a type that contains members that are references or const?
[英]How to copy members with const fields
我發現此代碼存在問題:
struct Example
{
const int k;
Example(int k) : k(k) {}
};
struct Board
{
Example table[4];
Board() {} // ???
};
我的問題是如何初始化表變量。 如果我提供默認構造函數,我將無法更改此const字段。 有解決方法嗎? 我也不能依賴拷貝構造函數。
你是說以下嗎?
#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} {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.