如果你真的需要使用数组(而不是std::vector),你可以使用这个例子:
#include <cstring>
#include <cstdint>
#include <iostream>
#include <initializer_list>
class A
{
private:
static const uint8_t MAX_LENGTH = 10;
uint8_t length;
uint8_t arr[MAX_LENGTH];
public:
A(uint8_t _length, const uint8_t array[]): length(_length)
{
if (length > MAX_LENGTH) { // to prevent copying out of memory
length = MAX_LENGTH;
}
std::memcpy(arr, array, length);
}
A(std::initializer_list<uint8_t> l): length(l.size())
{
if (length > MAX_LENGTH) { // to prevent copying out of memory
length = MAX_LENGTH;
}
std::initializer_list<uint8_t>::iterator it = l.begin();
for (uint32_t i = 0; (i < length) || (it == l.end()); ++i, ++it) {
arr[i] = *it;
}
}
uint8_t printAllForExample() const {
for (uint32_t i = 0; i < length; ++i) {
std::cout << (int)arr[i] << " ";
}
std::cout << std::endl;
}
uint8_t getLengthForExample() const {
return length;
}
};
int main() {
std::cout << "A_CONST_1:" << std::endl;
const A A_CONST_1{23};
A_CONST_1.printAllForExample();
std::cout << "A_CONST_2:" << std::endl;
const A A_CONST_2{};
std::cout << (int)A_CONST_2.getLengthForExample() << std::endl;
A_CONST_2.printAllForExample();
std::cout << "A_CONST_3:" << std::endl;
const A A_CONST_3{0,1,2,3,4,5,6,7,8,9};
std::cout << (int)A_CONST_3.getLengthForExample() << std::endl;
A_CONST_3.printAllForExample();
std::cout << "A_CONST_4:" << std::endl;
const A A_CONST_4{0,1,2,3,4,5,6,7,8,9,10,11,12};
std::cout << (int)A_CONST_4.getLengthForExample() << std::endl;
A_CONST_4.printAllForExample();
uint8_t data[] = {30,40,50};
std::cout << "A_CONST_5:" << std::endl;
const A A_CONST_5(3, data);
std::cout << (int)A_CONST_5.getLengthForExample() << std::endl;
A_CONST_5.printAllForExample();
return 0;
}