。h文件中声明静态const向量的错误和.cpp文件中定义的错误

问题描述 投票:0回答:1

我只是想在我的日期类中添加一些静态常量向量。编译器错误如下。这是我的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文件中所作定义的错误。我在这里无法正确格式化错误。有人可以告诉我我在做什么错吗?

c++ vector header implementation
1个回答
0
投票

在两个(13)对象的声明/定义之后,您不需要std::vector;实际上,您无法拥有它们。在标题中,您只需要声明向量;在源文件中,初始化器列表将告诉编译器这些向量应包含的内容。

说明:尽管您可以将const std::vector<int> dinMon(13)之类的语句作为“独立式”代码(它将使用13个元素构造所述向量),但是您不能在静态类的declaration中执行此操作成员:毕竟,这只是一个声明。因此,仅是简单的向量类型-然后定义(在Data.cpp中)必须匹配,因此也不能在其中有(13)

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

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) {
}
© www.soinside.com 2019 - 2024. All rights reserved.