C++ How to declare and initialize a vector inside a class -


i print out vector "colors" using member function "print".

/* inside .h file */ class color { public:     void print();  private:     std::vector<std::string> colors; = {"red", "green", "blue"}; };  /* inside .cpp file */  void color::print()  {      cout << colors << endl; } 

but error message saying:

implicit instantiation of undefined template. 

at declaration , initialization of vector "colors" inside class body

and warning:

in class initialization of non-static data member c++11 extension. 

you had lot of issues:

  1. writing once std:: , leave it.
  2. syntax error: std::vector<std::string> colors; = {"red", "green", "blue"};

                                                ^  
  3. you must iterate through vector in order items.

this code works , displays want:

#include <string> #include <iostream> #include <vector>  /* inside .h file */ class color { public:     void print();  private:     std::vector<std::string> colors = {"red", "green", "blue"}; };  /* inside .cpp file */  void color::print()  {      ( const auto & item : colors )     {         std::cout << item << std::endl;     } }  int main() {     color mycolor;      mycolor.print(); } 

live example


Comments

Popular posts from this blog

javascript - Confirm a form & display message if form is valid with JQuery -

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -