如何从静态向量中访问 class 个元素?
How to access class elements from static vector?
我在同一个 class 中有一个 class Town
的静态向量,我正在尝试访问它的元素。
代码:
// 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
是一个指向向量的指针,但它可能应该是一个向量:
// 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;
我在同一个 class 中有一个 class Town
的静态向量,我正在尝试访问它的元素。
代码:
// 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
是一个指向向量的指针,但它可能应该是一个向量:
// 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;