我正在编写一个程序,在该程序中我从 C++ 中的另一个类继承并重写了几个方法。因为我只想在这些方法中添加一行,所以我尝试在基类中调用该方法并在其下方添加一行。我收到以下错误。
"Unhandled exception at 0x00FA4456 in Ch.12.exe: 0xC0000005: Access violation reading location 0x67525A64."
这是我在java中最接近“超级”的(据我所知)。
类的简化版
using namespace std;
#include <iostream>
#include <string>
#include "dateType2.h"
class extDateType : public dateType
{
private:
string monthString;
void updateMonthString()
{
string months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
monthString = months[getMonth()];
}
public:
void printDateString()
{
string months[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
cout << months[getMonth()];
cout << " ";
cout << getYear();
}
extDateType(int month, int day, int year)
{
dateType(month, day, year);
updateMonthString();
}
void addDays(int x)
{
dateType::addDays(x);
updateMonthString();
}
};
int main()
{
extDateType x(2, 25, 1996);
x.addDays(10);
x.printDateString();
system("pause");
return 0;
}
基类的简化版本
using namespace std;
#include <iostream>
#include <string>
class dateType
{
private:
int dMonth;
int dDay;
int dYear;
bool isLeapYear;
public:
dateType(){}
void addDays(int x)
{
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
dDay += x;
for(int i = dMonth-1; dDay > days[i]; i++)
{
dDay -= days[i];
dMonth++;
if(dMonth == 13)
{
dMonth = 0;
dYear++;
}
i = i % 11;
}
}
dateType(int month, int day, int year)
{
isLeapYear = false;
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(month > 0 && month <= 12)
{
if(month == 2)
{
if(year % 4 == 0)
{
isLeapYear = true;
if(day > 0 && day <= 29)
{
dMonth = month;
dDay = day;
dYear = year;
}
else
{
cout << "Error" << endl;
dMonth = 1;
dDay = 1;
dYear = 2000;
}
}
else
{
isLeapYear = false;
if(day > 0 && day <= 28)
{
dMonth = month;
dDay = day;
dYear = year;
}
else
{
cout << "Error" << endl;
dMonth = 1;
dDay = 1;
dYear = 2000;
}
}
}
else
{
if(day > 0 && day <= days[month-1])
{
dMonth = month;
dDay = day;
dYear = year;
}
else
{
cout << "Error" << endl;
dMonth = 1;
dDay = 1;
dYear = 2000;
}
}
}
else
{
cout << "Error" << endl;
dMonth = 1;
dDay = 1;
dYear = 2000;
}
}
};
使用 Visual Studio 2012。如果有人能帮我找出问题所在,将不胜感激