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:
- writing once
std::
, leave it. syntax error:
std::vector<std::string> colors; = {"red", "green", "blue"};
^
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
Post a Comment