我尝试编译非常简单的代码:
struct T {
int a[3];
int b;
int c;
};
int main() {
const int as[3] = { 5, 6, 7, };
const T t {
as, 2, 3,
};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它给了我很奇怪的错误:
t.cpp: In function 'int main()':
t.cpp:11:5: error: array must be initialized with a brace-enclosed initializer
};
^
Run Code Online (Sandbox Code Playgroud)
根据我的理解,编译器希望我在一个地方初始化所有内容.如何单独初始化字段,然后在初始化结构时使用它们?
Dei*_*Dei 22
数组既不是可复制的,也不是可复制的.如果您可以访问C++ 11及更高版本,则可以使用std::array.
#include <array>
struct T {
std::array<int, 3> a;
int b;
int c;
};
int main() {
const std::array<int,3> as = { 5, 6, 7, };
const T t {
as, 2, 3,
};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
否则,您必须滚动循环并单独复制元素.
Bat*_*eba 11
C++数组不是可复制构造的,因此编译将失败.然而,
struct T {
int a[3];
int b;
int c;
};
int main() {
const T t {
{5, 6, 7, }, 2, 3,
};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是一种替代方案,尽管它确实丢弃了显式as变量.
参考:http://en.cppreference.com/w/cpp/concept/CopyConstructible
| 归档时间: |
|
| 查看次数: |
1728 次 |
| 最近记录: |