现在有一种方法可以使用C ++ 11中的初始化列表初始化固定大小的char数组吗?(Is there now a way to initialize a fixed size array of cha

编程入门 行业动态 更新时间:2024-10-17 12:31:47
现在有一种方法可以使用C ++ 11中的初始化列表初始化固定大小的char数组吗?(Is there now a way to initialize a fixed size array of char using initializer lists in C++11?)

我有一个类似这样的类:

class A { char _s[6]; public: A(const char s[6]) : _s{s[0], s[1], s[2], s[3], s[4], s[5]} { } };

这是使用C ++ 11初始化列表为char[] (或任何其他基本类型数组)初始化_s的唯一方法吗?

I have a class similar to this:

class A { char _s[6]; public: A(const char s[6]) : _s{s[0], s[1], s[2], s[3], s[4], s[5]} { } };

Is this the only way to initialze _s using C++11 initializer-list for char[] (or any other basic type array)?

最满意答案

class A { std::array<char, 6> _s; public: A(std::array<char, 6> s) : _s(s) {} }; int main() { std::array<char, 6> s; A a{s}; }

或者,如果您想避免将数组复制到构造函数中:

class A { std::array<char, 6> _s; public: A(std::array<char, 6> const &s) : _s(s) {} }; int main() { std::array<char, 6> s; A a{s}; }

你应该知道你的构造函数A(const char s[6])不是一个数组,而是一个指针。 它与A(char const *s)完全相同,因此构造函数不知道传入的数组大小是多少。 这只是关于原始数组的奇怪事情之一,也是不使用它们的众多原因之一。

class A { std::array<char, 6> _s; public: A(std::array<char, 6> s) : _s(s) {} }; int main() { std::array<char, 6> s; A a{s}; }

Or if you want to avoid copying the array into the constructor:

class A { std::array<char, 6> _s; public: A(std::array<char, 6> const &s) : _s(s) {} }; int main() { std::array<char, 6> s; A a{s}; }

You should be aware that your constructor A(const char s[6]) does not take an array, but a pointer. It's identical to A(char const *s), so the constructor has no idea what the size of the array you pass in is. This is just one of those bizarre things about raw arrays and one of the many reasons not to use them.

更多推荐

本文发布于:2023-07-14 14:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1105094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   有一   可以使用   数组   种方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!