Home > Blockchain >  How to push objects to a static vector while in the contructor of a class in C
How to push objects to a static vector while in the contructor of a class in C

Time:01-27

I need to get in a vector the names of some cities as soon as they are created... In order to accomplish that I created a static vector for the class City, however when I try to compile my code I get the error

error: lvalue required as unary '&' operand
          this->cities.push_back(&this);
                                   ^~~~

What am I doing wrong?

My code is the following...

#include <iostream>
#include <ctime>
#include <vector>

using namespace std;

class City
{
private:
     string name;
     static vector<City *> cities;

public:
     string getName() { return name; }
     City(string name) : name{name}
     {
          this->cities.push_back(&this);
     };
     ~City(){};
} hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"};

int main()
{
}

CodePudding user response:

this is already a City* pointer, so drop the & from &this.

Also, don't forget to actually define the static vector object.

Also, you should account for the class' copy/move constructors and destructor, to make sure you don't miss adding pointers, or leave behind dangling pointers.

Try this:

#include <iostream>
#include <ctime>
#include <vector>

using namespace std;

class City
{
private:
     string name;
     static vector<City *> cities;

public:
     string getName() { return name; }

     City(string name) : name{name}
     {
          cities.push_back(this);
     }

     City(const City &src) : name{src.name}
     {
          cities.push_back(this);
     }

     City(City &&src) : name{std::move(src.name)}
     {
          cities.push_back(this);
     }

     ~City()
     {
          cities.erase(std::find(cities.begin(), cities.end(), this));
     }
};

vector<City *> City::cities;

City hongKong{"Hong Kong"}, bangkok{"Bangkok"}, macau{"Macau"}, singapura{"Singapura"}, londres{"Londres"}, paris{"Paris"}, dubai{"Dubai"}, delhi{"Delhi"}, istambul{"Istambul"}, kuala{"Kuala"}, lumpur{"Lumpur"}, novaIorque{"Nova Iorque"}, antalya{"Antalya"}, mumbai{"Mumbai"}, shenzen{"Shenzen"}, phuket{"Phuket"};

int main()
{
}
  •  Tags:  
  • Related