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

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -