如何实例化对象的静态向量? [英] How to instantiate a static vector of object?
问题描述
我有一个类A,它具有对象的静态向量.这些对象属于B类
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;
}
在函数InstantiateVector()
In function InstantiateVector()
for (i=0; i < 5; i++) {
B b = B();
vector<B>.push_back(b);
}
但是使用Visual Studio 2008时出现编译错误:无法解析的外部符号... 是否可以使用上述方法实例化静态向量?为了创建对象b,必须从输入文件中读取一些数据,并将其存储为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
还是不可能,只有简单的静态向量才可能?我在某处读到要实例化静态向量,您必须首先定义const int a [] = {1,2,3},然后将a []复制到向量中
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 int a[] = {1,2,3}, and then copy a[] into vector
推荐答案
您必须提供vector_of_b
的定义,如下所示:
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;
请注意,您的InstantiateVector()
制作了很多不必要的副本,这些副本可能(也可能没有)被优化了.
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());
}
实际上,对于这个仅默认构造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);
这篇关于如何实例化对象的静态向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!