大家好,我正在尝试用 C++ 创建一个日期类,它显示默认日期、显示较短的设定日期、显示较长的设定日期,只显示设定的年份。但是,当我输入数据时,我正在尝试显示类的内容,但出现错误“使用未声明的标识符‘setDate’
这是头文件代码:
#ifndef dateClass_h
#define dateClass_h
using namespace std;
class DateObj
{
public:
int setDate(int month, int day, int year);
void shortDate(int month, int day, int year);
void longDate(string month, int day, int year);
//return the year
int getYear(int year){
return year;
}
private:
int month;
int day;
int year;
};
#endif /* dateClass_h */
这是我的实现文件代码:
#include <stdio.h>
#include <iostream>
#include <string>
#include "dateClass.h"
using namespace std;
//setDate Method
int DateObj::setDate(int month, int day, int year){
//setMonth = month;
//day = setDay;
//year = setYear;
//check to make sure month is between 1 - 12.
if(month < 1 || month > 12){
cout << "This is an invalid Month. Please enter a month that is between 1 and 12: " << endl;
}
//check to make sure day is between 1 -31.
if(day < 1 || day > 31){
cout << "This is an invalid Day. Please enter a day that is between 1 and 31: " << endl;
}
//check to make sure year is greater than zero.
if(year < 0){
cout << "This is an invalid Year. Please enter a year that is greater than Zero" << endl;
}
return setDate(month,day,year);
}
这是我的主要程序代码:
#include <iostream>
#include <string>
#include "dateClass.h"
using namespace std;
int main() {
DateObj myDate;
myDate.setDate(12, 25, 2016); //set the date to Dec 25, 2016.
cout << "The current date is: " << setDate() << endl;
return 0;
}
我只想知道为什么会出现此错误以及我需要在我的类或主程序中修复什么。
编辑 我得到了要编译的程序,但在返回 setDate(月、日、年)断点时出现以下错误“EXC_BAD_ACCESS(代码=2,地址=0x7fff5f3fffe8)”。
#include <iostream>
#include <string>
#include "dateClass.h"
using namespace std;
int main() {
DateObj myDate;
myDate.setDate(12,25,2016); //set the date to Dec 25, 2016.
cout << "The current date is: " << myDate.setDate(12, 25, 2016) << endl;
return 0;
}
最佳答案
您的 shortDate
函数似乎没有实现。
您的头文件中有它,但您的 dateClass.cpp 文件中似乎没有。您需要在 dateClass.cpp 文件中实现它,类似于您为 setDate
所做的。
您收到错误是因为它找不到任何实现。
关于c++ - 如何显示我的 C++ 类的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538342/