供参考:
//dateclass.h
#include <stdio.h>
class Date
{
public:
void setdate(int y, int m, int d);
void printdate();
private:
int year, month, day;
};
void Date::setdate(int y,int m,int d)
{
year = y; month = m; day = d;
}
void Date::printdate()
{
printf("今天的日期是%d年%d月%d日", year, month, day);
}
//dateclass.cpp
//#include "dateclass.h"
//#include <stdio.h>
int main()
{
int y, m, d;
Date D;
printf("请输入年 月 日\n");
scanf("%d%d%d", &y, &m, &d);
D.setdate(y, m, d);
D.printdate();
return 0;
}
c++的版本:
CL_date.h
//.h文件不加namespace,需要用到的一律在用到的地方加声明
//比如function(string s),由于没有加using namespace std会报错,可以写成function(std::string s)
#include<iostream>//需要用到的头文件可以统一写在.h里面,.cpp文件就可以通过包含此.h文件达到包含这些头文件的效果
class CL_Date {
public:
CL_Date();//构造函数
CL_Date(int _year, int _month, int _day);//构造函数的重载
~CL_Date();//析构函数
void SetDate(int _year, int _month, int _day);//设置日期的函数
void DispDate();//展示函数
private:
int year;
int month;
int day;
};
.cpp文件
#include"CL_Date.h"//这个一定要加
//#include<iostream>在CL_Date.h文件里面有这个头文件
using namespace std;
CL_Date::CL_Date() {
this->year = 0;
this->month = 0;
this->day = 0;
}
CL_Date::CL_Date(int _year, int _month, int _day) {
this->year = _year;
this->month = _month;
this->day = _day;
}
CL_Date::~CL_Date() {
}
void CL_Date::SetDate(int _year, int _month, int _day) {
this->year = _year;
this->month = _month;
this->day = _day;
}
void CL_Date::DispDate() {
cout << "今天的日期是" << this->year << "年" << this->month << "月" << this->day << "日" << endl;
}
主函数的调用:
#include"CL_Date.h"
using namespace std;
int main()
{
CL_Date myCL;//声明类
cout << "请输入年月日" << endl;
int year, month, day;
cin >> year >> month >> day;//输入
myCL.SetDate(year, month, day);//设置
myCL.DispDate();//展示
system("pause");
return 0;
}