我刚刚开始学习类,并且在我的主体中使用成员函数来打印所需的数据时遇到了困难。
这是我得到的错误:

main.cpp:在“int main()”函数中:
错误:要求在'd'中请求成员'printNumerical',该成员属于非类类型'Date(int,int,int)'
d.printNumerical();
^

错误:请求“d”中属于非类类型“Date(int,int,int)”的成员“printMonth”
d.printMonth();
^

错误:请求“d”中属于非类类型“Date(int,int,int)”的成员“printDateFirst”
d.printDateFirst();
^

这是我的主要内容:

int main ()
{
int Day, Month, Year;

cout << "date information: ";
cin >> Day;
cin >> Month;
cin >> Year;

cout << Day << " " << Month << " " << Year << endl;

Date d (int Day, int Month, int Year);

//where I am having issues
d.printNumerical();
d.printMonth();
d.printDateFirst();

return 0;
}

这是我的类定义Date.h
class Date
{
private:
int month,
    day,
    year;

public:
Date(int Day,int Month,int Year); //constructor
Date();                           //constructor if not passed arguments
void printNumerical(); //functions to output in certain format
void printMonthFirst();
void printDateFirst();
};

这是Date.cpp
Date::Date()
{
month = 1;
day = 1;
year = 2001;
}

Date::Date(int Day, int Month, int Year)
{                                        //input validation
if((Month < 1) || (Month > 12) || (Day < 1) || (Day > 31) || (Year < 0))
{
month = 1;
day = 1;
year = 2001;
}
else{
        month = Month; //accept passed arguments if valid
        day = Day;
        year = Year;
}
}

void Date::printNumerical()
{
cout << month << "/" << day << "/" << year << endl;
}

void Date::printMonthFirst()
{
switch(month)
{
    case 1 : cout << "January ";
        break;
    case 2 : cout << "February ";
        break;
    case 3 : cout << "March ";
        break;
    case 4 : cout << "April ";
        break;
    case 5 : cout << "May ";
        break;
    case 6 : cout << "June ";
        break;
    case 7 : cout << "July ";
        break;
    case 8 : cout << "August ";
        break;
    case 9 : cout << "September ";
        break;
    case 10 : cout << "October ";
        break;
    case 11 : cout << "November ";
        break;
    case 12 : cout << "December ";
        break;
}
cout << day << ", " ;
cout << year << endl;
}

void Date::printDateFirst()
{
cout << day << " ";
switch(month)
{
    case 1 : cout << "January ";
        break;
    case 2 : cout << "February ";
        break;
    case 3 : cout << "March ";
        break;
    case 4 : cout << "April ";
        break;
    case 5 : cout << "May ";
        break;
    case 6 : cout << "June ";
        break;
    case 7 : cout << "July ";
        break;
    case 8 : cout << "August ";
        break;
    case 9 : cout << "September ";
        break;
    case 10 : cout << "October ";
        break;
    case 11 : cout << "November ";
        break;
    case 12 : cout << "December ";
        break;
}
cout << year << endl;
}

最佳答案

下一行:

Date d (int Day, int Month, int Year);

实际上是该函数的前向声明,它使用三个整数作为输入并返回Date对象。
Date d (Day, Month, Year); // proper construction

08-26 21:30
查看更多