Home > OS >  Unable to retrieve a static vector from inside a class
Unable to retrieve a static vector from inside a class

Time:01-27

I want to get a vector from the class City, however I am not able to see any of those cities generated, in the vector cities being displayed...

However I do know that they are being generated as I can see their names as well as the size being incremented being displayed in the constructor.

Contructor for: Hong Kong
1
Contructor for: Bangkok
2
Contructor for: Macau
3
Contructor for: Singapura
4
Contructor for: Londres
5
Contructor for: Paris
6
Contructor for: Dubai
7
Contructor for: Delhi
8
Contructor for: Istambul
9
Contructor for: Kuala
10
Contructor for: Lumpur
11
Contructor for: Nova Iorque
12
Contructor for: Antalya
13
Contructor for: Mumbai
14
Contructor for: Shenzen
15
Contructor for: Phuket
16

What am I doing wrong?? Bellow is my code:

As you can see I have commented out the destructor, however I am still unable to see any city in the vector, as calling the function display_cities() will render nothing but a 0, being displayed:

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

using namespace std;

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

public:
     static vector<string> getCidades() { return cities; }
     string getNome() { return nome; }
     City(string nome) : nome{nome}
     {
          this->cities.push_back(this->nome);
          cout << "Contructor for: "   this->nome << endl
               << this->cities.size() << endl;
     };
     // ~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"};

vector<string> City::cities;
void display_cities()
{
     vector<string> cities = City::getCidades();
     cout << cities.size() << endl;
     for (size_t i = 0; i < cities.size(); i  )
     {
          cout << cities[i] << endl;
     }
}

int main()
{

     display_cities();
     return 0;
}

CodePudding user response:

You have to create a city object in main. Try passing all those constructors in main as a city object. Also, I compile your original code with vs c 17 and it throws an exception.

int main() 
{
  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" };
  display_cities();
  return 0;
}
  •  Tags:  
  • Related