我有一个类似这样的类:
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.
更多推荐
发布评论