我有一个 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[] 复制到向量中
您必须提供以下定义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;
作为旁注,您的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());
}
事实上,对于这个简单的例子,你只是默认构建B
对象,最简洁的方法是将循环全部替换为:
// default constructs 5 B objects into the vector
vector_of_B.resize(5);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)