gpt4 book ai didi

c++ - 如何实例化对象的静态 vector ?

转载 作者:可可西里 更新时间:2023-11-01 16:27:31 25 4
gpt4 key购买 nike

我有一个类 A,它有一个对象的静态 vector 。对象属于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 时出现编译错误:未解析的外部符号...是否可以使用上述方法实例化静态 vector ?要创建对象 b,必须从输入文件中读取一些数据,并将其存储为 b 的成员变量

或者不可能,只有简单的静态 vector 是可能的?我在某处读到要实例化静态 vector ,必须先定义一个const int a[] = {1,2,3},然后将a[]复制到 vector 中

最佳答案

您必须按如下方式提供 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);

关于c++ - 如何实例化对象的静态 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7531981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com