【问题标题】:How to access class elements from static vector?如何从静态向量访问类元素?
【发布时间】:2020-10-18 14:40:48
【问题描述】:

我在同一个类中有一个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&lt;Town&gt; 没有名为 name 的成员

【问题讨论】:

  • 为什么towns 是指向向量的指针?
  • @ThomasSablik 我刚刚意识到有更简单的方法可以做我想做的事情(感谢您的回答),但主要想法是我很少使用指针,我想练习

标签: c++ class vector static member


【解决方案1】:

在您的代码中,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;

【讨论】:

  • 我不得不承认,我忘记了 .resize() 是一个东西,但不是也可以用指针来完成吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多