我发现我的程序有些bug,原因是因为我可以从类数组中访问数据
这是类代码
void Date::initialize(){
string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
};
这是头文件Date.h,上面的代码存储在Date.cpp中并使用main.cpp加载它
class Date{
private:
int day;
int month;
int year;
string monthNames[12];
int monthDays[12];
答案 0 :(得分:2)
void Date::initialize()
{
string monthNames[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
copy(monthNames, monthNames + 12, this->monthNames);
}
您创建一个本地数组,这是合乎逻辑的,因为您只能使用大括号初始化数组,而不能分配给它。所以你创建了一个本地数组。现在您需要将其复制到您的实际成员this->monthNames
。对于另一个阵列也是如此。看一下copy
函数。如果不允许使用stl算法,则可以使用旧的for循环进行复制。
答案 1 :(得分:2)
您刚刚定义了局部变量,因此您必须将其数据复制到初始化类属性。
void Date::initialize(){
// make the data static not to initialize them every time this function is called
static string monthNamesData[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
static int monthDaysData[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (size_t i = 0; i < sizeof(monthNames) / sizeof(*monthNames); i++){
monthNames[i] = monthNamesData[i];
}
for (size_t i = 0; i < sizeof(monthDays) / sizeof(*monthDays); i++){
monthDays[i] = monthDaysData[i];
}
}
答案 2 :(得分:1)
数组monthNames
和monthDays
被声明为成员函数initialize
void Date::initialize(){
string monthNames[] =
^^^^^^^^^^^^^^^^^^^
{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
^^^^^^^^^^^^^^^
};
退出函数后会将其销毁。
尝试改为
#include <array>
//...
class Date{
private:
int day;
int month;
int year;
std::array<string, 12> monthNames;
std::array<int, 12> monthDays;
//...
void Date::initialize(){
monthNames = { {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} };
monthDays = { {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} };
};
答案 3 :(得分:1)
私有成员变量只能通过PUBLIC成员函数在其类外部访问(但此函数的声明必须在我认为您已经完成的类中)。你的initialize()函数是公开的吗?因为我不这么认为。对于Classes,一切都是PRIVATE BY DEFAULT,所以请确保你的initialize()在class中声明,但在PUBLIC标题下。