0

I am simply trying to add some static constant vectors to my date class. Compiler errors given below. Here is my Date.h file.

#include <vector>
#include <string>

class Date {
   private:
      int month;
      int day;
      int year;
      static const std::vector<std::string> monthNames(13);
      static const std::vector<int> daysInMonths(13);
   public:
      Date();
      Date(int month, int day, int year);
}

Now my Date.cpp file

#include "Date.h"
#include <vector>
#include <string>

const std::vector<std::string> Date::monthNames(13) {"","January","February","March","April","May",
      "June","July","August","September","October","November","December"};
const std::vector<int> Date::daysInMonths(13) {0,31,28,31,30,31,30,31,31,30,31,30,31};

Date::Date() : month(1), day(1), year(1900){
}

Date::Date(int month, int day, int year) : month(month), day(day), year(year) {
}

My g++ compiler gives me errors I cannot decipher for my declaration of my vectors in the .h file and for the definitions I made in the .cpp file. I cannot get the errors to format well in here. Can someone please show me what I am doing wrong?

William S
  • 167
  • 2
  • 10

1 Answers1

1

You don't need the (13) after the declarations/definitions of your two std::vector objects; in fact, you cannot have them. In the header, you only need to declare the vectors; in your source file, the initializer lists will tell the compiler what those vectors should contain.

Explanation: Although you can have a statement like const std::vector<int> dinMon(13) as "free-standing" code (it will construct the said vector with 13 elements), you cannot do this in the declaration of a static class member: this is, after all, only a declaration. So, just the plain vector type - and then the definition (in Data.cpp) has to match, so you can't have the (13) there, either.

Also, you are missing a ; after the declaration of your Date class (that is, after the closing curly brace in your header file).

Date.h:

class Date {
private:
    int month;
    int day;
    int year;
    static const std::vector<std::string> monthNames;
    static const std::vector<int> daysInMonths;
public:
    Date();
    Date(int month, int day, int year);
}; // You forgot the semicolon here!

Date.cpp:

#include "Date.h"
// #include <vector> // Don't need to re-include these, as they are already ...
// #include <string> // ... included by "Date.h"
const std::vector<std::string> Date::monthNames {
    "", "January", "February", "March", "April", "May",
    "June", "July", "August", "September", "October", "November", "December"
};
const std::vector<int> Date::daysInMonths { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Date::Date() : month(1), day(1), year(1900) {
}

Date::Date(int month, int day, int year) : month(month), day(day), year(year) {
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83