在 .h 文件中声明静态常量向量时出错,在 .cpp 文件中定义时出错

Errors declaring static const vector in .h file and errors in definitions in .cpp file

我只是想向我的日期添加一些静态常量向量 class。下面给出的编译器错误。 这是我的 Date.h 文件。

#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);
}

现在我的 Date.cpp 文件

#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) {
}

我的 g++ 编译器给出了我无法破译我在 .h 文件中的向量声明和我在 .cpp 文件中所做的定义的错误。我无法在此处正确格式化错误。有人可以告诉我我做错了什么吗?

您不需要两个 std::vector 对象的 declarations/definitions 之后的 (13);事实上,你不能拥有它们。在header中,你只需要声明vector;在您的源文件中,初始化列表将告诉编译器这些向量应该包含什么。

说明:虽然您可以将 const std::vector<int> dinMon(13) 之类的语句作为 "free-standing" 代码(它将构造具有 13 个元素的所述向量),但您不能在 declaration 静态 class 成员:毕竟,这只是一个声明。所以,只有普通向量类型 - 然后定义(在 Data.cpp 中)必须匹配,所以你也不能在那里有 (13)

此外,您在 Date class 声明之后(即在头文件中的右大括号之后)缺少 ;

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) {
}