3

我在同一个类中有一个静态向量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.

4

1 回答 1

4

在您的代码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;
于 2020-06-28T10:19:17.130 回答