Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access class elements from static vector?

I have a static vector of class Town inside the same class, and I am trying to access it's elements.

Code:

// 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

I'm getting an error: class std::vector<Town> has no member named name.

like image 511
H-005 Avatar asked Jul 02 '26 06:07

H-005


1 Answers

In your code towns is a pointer to a vector but probably it should be a 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;

If you really want it to be a pointer you have to dereference the pointer

// 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;
like image 67
Thomas Sablik Avatar answered Jul 04 '26 20:07

Thomas Sablik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!