gpt4 book ai didi

c++ - 如何从静态 vector 访问类元素?

转载 作者:行者123 更新时间:2023-12-01 14:18:15 25 4
gpt4 key购买 nike

我有一个 class Town 的静态 vector 在同一个类中,我正在尝试访问它的元素。

代码:

// town.h
class Town
{
public:
static int nrOfTowns;
static std::vector<Town> *towns;
std::string name;
};

int Town::nrOfTowns = 0;
std::vector<Town> *Town::towns = NULL;

// main.cpp
/* code */
Town::towns = new std::vector<Town> (Town::nrOfTowns); // initializing vector
Town::towns[0].name; // gives me an error

我收到一个错误: class std::vector<Town>没有名为 name 的成员.

最佳答案

在您的代码中,towns 是一个指向 vector 的指针,但它可能应该是一个 vector :

// town.h
class Town
{
public:
static int nrOfTowns;
static std::vector<Town> towns;
std::string name;
};

int Town::nrOfTowns = 0;
std::vector<Town> Town::towns;

// main.cpp
/* code */
Town::towns.resize(Town::nrOfTowns);
Town::towns[0].name;

如果你真的想让它成为一个指针,你必须取消对指针的引用

// town.h
class Town
{
public:
static int nrOfTowns;
static std::vector<Town> *towns;
std::string name;
};

int Town::nrOfTowns = 0;
std::vector<Town> *Town::towns = nullptr;

// main.cpp
/* code */
Town::towns = new std::vector<Town> (Town::nrOfTowns); // initializing vector
(*Town::towns)[0].name; // gives me an error
delete Town::towns;

关于c++ - 如何从静态 vector 访问类元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62621106/

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