gpt4 book ai didi

c++ - 在 .h 文件中声明静态常量 vector 时出错,在 .cpp 文件中定义时出错

转载 作者:行者123 更新时间:2023-11-28 04:08:38 25 4
gpt4 key购买 nike

我只是想在我的日期类中添加一些静态常量 vector 。下面给出的编译器错误。这是我的 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 文件中的 vector 声明和我在 .cpp 文件中所做的定义的错误。我无法在此处正确格式化错误。有人可以告诉我我做错了什么吗?

最佳答案

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

解释:尽管您可以使用类似 const std::vector<int> dinMon(13) 的语句作为“独立”代码(它将构造具有 13 个元素的所述 vector ),您不能在静态类成员的 声明 中执行此操作:毕竟,这只是一个声明。所以,只是简单的 vector 类型 - 然后定义(在 Data.cpp 中)必须匹配,所以你不能有 (13)那里,要么。

此外,您还缺少一个 ;在您的 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!

日期.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) {
}

关于c++ - 在 .h 文件中声明静态常量 vector 时出错,在 .cpp 文件中定义时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com