不久前,我被赋予了将Java程序转换为C ++的任务。
我已经这样做了,我开始遇到一些对我来说似乎没有任何意义的奇怪错误。
该程序包含三个文件。 main.ccp,date.ccp和date.h。
main.ccp
#include <cstdlib>
#include <iostream>
#include "Date.h"
using namespace ::std;
string weekday(Date date);
int main() {
int day, month, year;
cout << "What date (d m y)? ";
cin >> day >> month >> year;
Date event = Date(day, month, year);
cout << ("That was a " + weekday(event));
return 0;
}
string weekday(Date date) {
const string days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
Date trial = Date(1, 1, 1);
int weekday = 6;
if (Date::precedes(trial)) {
return "Mysteryday";
} else {
while (trial.precedes(date)) {
trial.advance();
weekday = (weekday + 1) % 7;
}
return days[weekday];
}
}
Date.ccp
#include "Date.h"
Date::Date(int day, int month, int year) {
day_ = day;
month_ = month;
year_ = year;
}
int Date::getDay () {
return day_;
}
void Date::setDay (int day) {
day_ = day;
}
int Date::getMonth () {
return month_;
}
void Date::setMonth (int month) {
month_ = month;
}
int Date::getYear () {
return year_;
}
void Date::setYear (int year) {
year_ = year;
}
bool Date::isLeapYear () {
bool lear = false;
if (this->year_ <= 1752) {
if (this->year_ % 4 == 0) {
lear = true;
}
}
else {
lear = false;
}
if (this->year_ > 1752) {
if (this->year_ % 4 == 0 && this->year_ % 100 != 0) {
lear = true;
}
else if (this->year_ % 4 == 0 && this->year_ % 100 == 0 && this->year_ % 400 == 0) {
lear = true;
}
else {
lear = false;
}
}
return lear;
}
int Date::daysInMonth () {
// "30 days hath September ... "
switch (this->month_) {
case 9 :
case 4 :
case 6 :
case 11 :
return 30;
default :
return 31;
case 2 :
return this->isLeapYear() ? 29 : 28;
}
}
void Date::advance () {
this->day_;
if (this->day_ == 3 && this->month_ == 9 && this->year_ == 1752) {
day_ = 14;
month_ = 9;
year_ = 1752;
}
if (this->day_ > this->daysInMonth()) {
this->day_ = 1;
this->month_++;
}
if (this->month_ > 12) {
this->month_ = 1;
this->year_++;
}
}
bool Date::precedes (Date date) {
return this->year_ < date->year_
|| this->year_ == date->year_ && this->month_ < date->month_
|| this->year_ == date->year_ && this->month_ == date->month_ && this->day_ < date->day_;
}
Date.h
#ifndef DATE_H
#define DATE_H
class Date {
public:
Date (int day, int month, int year);
int getDay();
void setDay();
int getMonth();
void setMonth();
int getYear();
void setYear();
bool isLeapYear();
int daysInMonth();
void advance();
bool precedes(Date date);
private:
int day_;
int month_;
int year_;
};
#endif /* DATE_H */
我编译时似乎遇到了很多相同的错误。
Date.cpp:97:95:错误:' - &gt;'的基本操作数具有非指针类型'Date'
我不确定我是否做了正确的声明。
答案 0 :(得分:3)
在课程结束}
之后,您忘了加分号。
答案 1 :(得分:0)
Date
的类定义不以分号结尾。因为你在main.cpp中#include
这个文件,所以标题之后的第一个语句是由于这个语法错误而不会解析的语句;因此你在错误的地方得到错误。