How to instantiate a static vector of object?
I have a class A, which has a static vector of objects. The objects are of class B
class A {
public:
static void InstantiateVector();
private:
static vector<B> vector_of_B;
}
In function InstantiateVector()
for (i=0; i < 5; i++) {
B b = B();
vector<B>.push_back(b);
}
But I have compilation error using visual studio 2008: unresolved external symbol... Is it possible to instantiate static vector using above method? For object b to be created, some data has to be read from input file, and stored as member variables of b
Or it is not possible, and only simple static vector is possible? I read somewhere that to instantiate static vector, you must first define a const in开发者_Python百科t a[] = {1,2,3}, and then copy a[] into vector
You have to provide the definition of vector_of_b
as follows:
// A.h
class A {
public:
static void InstantiateVector();
private:
static vector<B> vector_of_B;
};
// A.cpp
// defining it fixes the unresolved external:
vector<B> A::vector_of_B;
As a side note, your InstantiateVector()
makes a lot of unnecessary copies that may (or may not) be optimized away.
vector_of_B.reserve(5); // will prevent the need to reallocate the underlying
// buffer if you plan on storing 5 (and only 5) objects
for (i=0; i < 5; i++) {
vector_of_B.push_back(B());
}
In fact, for this simple example where you are just default constructing B
objects, the most concise way of doing this is simply to replace the loop all together with:
// default constructs 5 B objects into the vector
vector_of_B.resize(5);
Add the definition of the static member object to your class implementation file:
#include "A.h"
std::vector<B> A::vector_of_B;
Or rather, absorbing and obviating the initialization routine:
std::vector<B> A::vector_of_B(5, B()); // same effect as `A::InstantiateVector()`
Note: In C++98/03, vector_of_B(5)
and vector_of_B(5, B())
are identical. In C++11 they're not.
You can either use a static helper or use boost::assign
1>using a small helper:
#include <boost\assign.hpp>
class B{};
class A {
public:
static bool m_helper;
static bool InstantiateVector()
{
for (int i=0; i < 5; ++i)
{
B b;
vector_of_B.push_back(b);
}
return true;
}
private:
static vector<B> vector_of_B;
};
bool A::m_helper = InstantiateVector();//helper help initialize static vector here
2> Use boost::assign which is eaiser, one line is enough:
vector<B> A::vector_of_B = boost::assign::list_of(B())(B())(B())(B())(B());
精彩评论