Mic*_*ael 9 c++ instantiation static-members
我有一个A类,它有一个静态的对象向量.对象属于B类
class A {
public:
static void InstantiateVector();
private:
static vector<B> vector_of_B;
}
Run Code Online (Sandbox Code Playgroud)
在函数InstantiateVector()中
for (i=0; i < 5; i++) {
B b = B();
vector<B>.push_back(b);
}
Run Code Online (Sandbox Code Playgroud)
但我使用visual studio 2008编译错误:未解析的外部符号......是否可以使用上述方法实例化静态向量?对于要创建的对象b,必须从输入文件中读取一些数据,并将其存储为b的成员变量
或者它是不可能的,只有简单的静态向量是可能的?我在某处读到要实例化静态向量,首先必须定义一个const int a [] = {1,2,3},然后将[]复制到向量中
Cha*_*had 17
您必须提供vector_of_b如下定义:
// 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;
Run Code Online (Sandbox Code Playgroud)
作为附注,您InstantiateVector()制作了许多可能(或可能不)优化的不必要副本.
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());
}
Run Code Online (Sandbox Code Playgroud)
实际上,对于这个只是默认构造B对象的简单示例,最简洁的方法是简单地将所有循环替换为:
// default constructs 5 B objects into the vector
vector_of_B.resize(5);
Run Code Online (Sandbox Code Playgroud)