我试图不使用STL来初始化一个类的私有(private)成员数组(因为我正在使用的Arduino 微 Controller 平台不支持它)。这意味着没有 std::array
或 std::initializer_list
等
以下使用 gcc 5.4.0 和 avr-gcc 4.9.2 编译正确,但是 that seems to be a bug . Clang 抛出一个错误,提示 error: array initializer must be an initializer list
(正如预期的那样)。
代码
#include <iostream>
#define PRINTFN() std::cout << __PRETTY_FUNCTION__ << std::endl
class Object {
public:
Object(int number) : number(number) { PRINTFN(); }
Object(const Object &o) : number(o.number) { PRINTFN(); }
void print() { std::cout << "The number is " << number << std::endl; }
private:
const int number;
};
template <size_t N>
class ManyObjects {
public:
ManyObjects(const Object(&objects)[N]) : objects(objects) {}
void print() {
for (Object &object : objects)
object.print();
}
private:
Object objects[N];
};
int main() {
ManyObjects<3> many = {{1, 2, 3}};
many.print();
}
输出
Object::Object(int)
Object::Object(int)
Object::Object(int)
Object::Object(const Object&)
Object::Object(const Object&)
Object::Object(const Object&)
The number is 1
The number is 2
The number is 3
初始化对象
的正确方法是什么?或者在给定的约束条件下是不可能的?
最佳答案
您可以使用可变参数模板:
在 ManyObjects
类中:
template <typename... _Args>
ManyObjects(_Args&&... arguments) :
objects { arguments... }
{
}
更多here
关于C++初始化对象的非静态成员数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421763/