I am doing a bit from Stroustrup's "Principles and practice" chapter 10, where he offers to create a table for converting numbers of months to their names and vice versa. That table is in a form of a string vector, which is then used by several functions declared in the header file of the program. I tried to go an easy way and declare + init the vector in the same header, so that all the functions could see it:
std::vector<std::string> monthNames(12);
monthNames[0] = "jan";
monthNames[1] = "feb";
monthNames[2] = "mar";
monthNames[3] = "apr";
monthNames[4] = "may";
monthNames[5] = "jun";
monthNames[6] = "jul";
monthNames[7] = "aug";
monthNames[8] = "sep";
monthNames[9] = "oct";
monthNames[10] = "nov";
monthNames[11] = "dec";
Now G++ does not seem to understand what I'm trying to do:
In file included from temperature.cpp:1:
./Temperature.h:48:1: error: C++ requires a type specifier for all declarations
monthNames[0] = "jan";
^~~~~~~~~~
./Temperature.h:49:1: error: C++ requires a type specifier for all declarations
monthNames[1] = "feb";
...
I understand in general, that declaring a global vector in a header is a poor practice, but in this example it seems to be a reasonable substitute for 12 {if...elses} in the functions that convert nums to month names and vice versa:
const std::string& intToMonth(int num) {
if ( num < 1 || num > 12 )
throw BadMonthException();
return monthNames[num-1];
}
So I have two questions:
1) Why would compiler not let me initialize the vector?
2) Is there a sexier way to make it all work (without a global vector)?