我在同一个类中有一个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;

10-06 10:00