簡體   English   中英

現在是否可以使用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的唯一方法嗎?

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) ,因此構造函數不知道您傳入的數組的大小。 這只是有關原始數組的怪異事情之一,也是不使用原始數組的眾多原因之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM