如何实例化对象的静态向量?
我有一个 A 类,它有一个静态对象向量。这些对象属于 B 类,
class A {
public:
static void InstantiateVector();
private:
static vector<B> vector_of_B;
}
在函数 InstantiateVector() 中,
for (i=0; i < 5; i++) {
B b = B();
vector<B>.push_back(b);
}
但我使用 Visual Studio 2008 时遇到编译错误:无法解析的外部符号... 是否可以使用上述方法实例化静态向量?对于要创建的对象 b,必须从输入文件读取一些数据,并将其存储为 b 的成员变量
或者这是不可能的,并且只能简单的静态向量?我在某处读到,要实例化静态向量,必须首先定义一个 const int a[] = {1,2,3},然后将 a[] 复制到向量中
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 int a[] = {1,2,3}, and then copy a[] into vector
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须提供
vector_of_b
的定义,如下所示:作为旁注,您的
InstantiateVector()
会生成大量不必要的副本,这些副本可能(也可能不会)被优化掉。事实上,对于这个简单的示例,您只是默认构造
B
对象,最简洁的方法是将循环全部替换为:You have to provide the definition of
vector_of_b
as follows:As a side note, your
InstantiateVector()
makes a lot of unnecessary copies that may (or may not) be optimized away.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:将静态成员对象的定义添加到类实现文件中:
或者更确切地说,吸收并消除初始化例程:
注意:在 C++98/03 中,
vector_of_B(5 )
和vector_of_B(5, B())
相同。在 C++11 中则不然。Add the definition of the static member object to your class implementation file:
Or rather, absorbing and obviating the initialization routine:
Note: In C++98/03,
vector_of_B(5)
andvector_of_B(5, B())
are identical. In C++11 they're not.您可以使用静态助手或使用 boost::assign
1>使用小助手:
2>使用 boost::assign 更容易,一行就足够了:
You can either use a static helper or use boost::assign
1>using a small helper:
2> Use boost::assign which is eaiser, one line is enough: