この問題に対してさまざまな解決策を試しましたが、ヘッダー ファイルでコンパイラがこのエラーを表示し続ける理由がわかりません。誰かが私に洞察を与えることができれば、それは非常にありがたいです. 編集:申し訳ありませんが、エラーが発生している行を忘れてしまいました。ヘッダー ファイルの次の行にあります。 Date(string mstr, int dd, int yy);
はい、私は this = new Date... が悪い解決策であることを知っています。
ヘッダ:
#include <string>
#ifndef DATE_H
#define DATE_H
class Date{
public:
Date(int mm, int dd, int yy);
Date(string mstr, int dd, int yy);
void print();
void printFullDate();
void prompt();
void setMonth(int);
void setDay(int);
void setYear(int);
int getMonth();
int getDay();
int getYear();
static const int monthsPerYear = 12;
private:
int month;
int day;
int year;
int checkDay(int);
};
#endif
そして、必要な場合の実装は次のとおりです(完全には完成していません。私が書いた関数のいくつかをテストしようとしているだけです):
#include <iostream>
#include <stdexcept>
#include "Date.h"
using namespace std;
Date::Date(int mm, int dd, int yy){
setMonth(mm);
setYear(yy);
setDay(dd);
}
Date::Date(string mstr, int dd, int yy){
cout << "It's working";
}
int Date::getDay(){
return day;
}
int Date::getMonth(){
return month;
}
int Date::getYear(){
return year;
}
void Date::setDay( int dd ){
day = checkDay(dd);
}
void Date::setMonth( int mm ){
if( mm > 0 && mm <= monthsPerYear)
month = mm;
else
throw invalid_argument("month must be 1-12");
}
void Date::setYear( int yy ){
year = yy;
}
int Date::checkDay( int testDay){
static const int daysPerMonth[ monthsPerYear + 1 ] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if( testDay > 0 && testDay <= daysPerMonth[ getMonth() ])
return testDay;
if( getMonth() == 2 && testDay == 29 && (getYear() % 400 == 0 || ( getYear() % 4 == 0 && getYear() % 100 != 0 ) ) )
return testDay;
throw invalid_argument("Invalid day for current month and year");
}
void Date::print(){
}
void Date::printFullDate(){
}
void Date::prompt(){
int userChoice = 1;
int mm, dd, yy;
string monthStr;
while(userChoice != 3){
cout << "Enter 1 for format: MM/DD/YYYY" << endl;
cout << "Enter 2 for format: Month DD, YYYY" << endl;
cout << "Enter 3 to exit" << endl;
cout << "Choice: " << endl;
cin >> userChoice;
while(userChoice < 1 || userChoice > 3){
cout << "Please enter a number 1 - 3 for the formats above." << endl;
cout << "Choice: " << endl;
cin >> userChoice;
}
if(userChoice != 3){
switch(userChoice){
case 1:
cout << "Enter Month (1 - 12): ";
cin >> mm;
setMonth(mm);
cout << "Enter Day of Month: ";
cin >> dd;
setDay(dd);
cout << "Enter Year: ";
cin >> yy;
setYear(yy);
break;
case 2:
cout << "Enter Month Name: ";
cin >> monthStr;
cout << "Enter Day of Month: ";
cin >> dd;
cout << "Enter Year: ";
cin >> yy;
this = new Date(monthStr, dd, yy);
break;
default:
break;
}
}
}
}