您在vector 的构造函数的第二个参数中传递的值按原样 传递给所创建的每个元素的复制构造函数。由于您正在创建Foo 对象的vector,第二个参数本身将是Foo 对象,因此您正在创建一个临时Foo,并将int 作为输入,然后将该临时参数传递给vector 中每个 Foo 实例的复制构造函数。
因此,与您正在寻找的语法最接近的是:
class Foo
{
public:
...
int a;
int Index;
Foo(int _x) : a(_x), Index(-1) {}
Foo(const Foo &_f) : a(_f.a) { Index = ++(const_cast<Foo&>(_f).Index); }
...
};
int main()
{
int a = 5;
// this (implicitly) creates a temp Foo object using the 'Foo(int)'
// constructor, and then copy-constructs the Foo objects in the
// vector passing that temp to the 'Foo(const Foo&)' constructor...
std::vector<Foo> Instances (30, a);
return 0;
}
Live Demo
但是,这是对 C++ 语言的明显不安全的滥用,所以不要使用它。
更安全的选择是在填充vector 后简单地初始化索引,例如:
class Foo
{
public:
...
int a;
int Index;
Foo(int _x) : a(_x), Index(-1) {}
...
};
int main()
{
int a = 5;
std::vector<Foo> Instances (30, a);
// yes, I know, you don't want to use the operator[], but it
// is a safer option...
for(size_t index = 0; index < Instances.size(); ++index)
Instances[index].Index = index;
// unless you use iterators instead...
/*
size_t index = 0;
for (std::vector<Foo>::iterator iter = Instances.begin(); iter != Instances.end(); ++iter)
iter->Index = index++;
*/
/*
size_t index = 0;
for (auto &f : Instances)
f.Index = index++;
*/
return 0;
}
Live Demo
更新:感谢 cmets 中的 François Andrieux,我有了另一个想法,涉及 std::generate_n() 以您想要的方式为您创建索引。虽然它不是您正在寻找的语法:
#include <vector>
#include <algorithm>
#include <utility>
struct MyIndexGenerator
{
int value;
int index;
MyIndexGenerator(int _value, int _first = 0) : value(_value), index(_first) {}
std::pair<int, int> operator()()
{
return std::make_pair(value, index++);
}
};
class Foo
{
public:
int x;
int Index;
Foo(const std::pair<int, int> &_x) : x(_x.first), Index(_x.second) {}
...
};
int main()
{
int a = 5;
std::vector<Foo> Instances;
Instances.reserve(30);
std::generate_n(std::back_inserter(Instances), 30, MyIndexGenerator(a));
return 0;
}
Live Demo