?? 12_2_3.c
字號:
/* ======================================== */
/* 程序?qū)嵗? 12_2_3.cpp */
/* 類的構(gòu)造函數(shù) */
/* ======================================== */
#include <iostream.h>
class date /* date類聲明 */
{
private:
int day; /* 成員資料聲明 */
int month;
int year;
int validDate(int d, int m, int y); /* 成員函數(shù)聲明 */
public:
date(); /* 構(gòu)造函數(shù)聲明 */
date(int d, int m, int y); /* 構(gòu)造函數(shù)聲明 */
int setDate(int d, int m, int y); /* 成員函數(shù)聲明 */
void printDate();
};
/* ---------------------------------------- */
/* 成員函數(shù): 檢查時(shí)間參數(shù)是否合法 */
/* ---------------------------------------- */
int date::validDate(int d, int m, int y)
{
/* 檢查日期數(shù)據(jù)是否在范圍內(nèi) */
if (d < 1 || d > 31) return 0;
if (m < 1 || m > 12) return 0;
if (y < 1900) return 0; /* 不在范圍內(nèi) */
return 1; /* 合法日期數(shù)據(jù) */
}
/* ---------------------------------------- */
/* 構(gòu)造函數(shù)(1): 設(shè)置成員數(shù)據(jù)初始值 */
/* ---------------------------------------- */
date::date()
{
day = 1; /* 設(shè)置日期 */
month = 1; /* 設(shè)置月份 */
year = 2001; /* 設(shè)置年份 */
}
/* ---------------------------------------- */
/* 構(gòu)造函數(shù)(2): 使用參數(shù)設(shè)置成員數(shù)據(jù)初始值 */
/* ---------------------------------------- */
date::date(int d, int m, int y)
{
if (validDate(d, m, y)) /* 檢查時(shí)間參數(shù)是否合法 */
{
day = d; /* 設(shè)置日期 */
month = m; /* 設(shè)置月份 */
year = y; /* 設(shè)置年份 */
}
else
{
date();
}
}
/* ---------------------------------------- */
/* 成員函數(shù): 設(shè)置時(shí)間的成員數(shù)據(jù) */
/* ---------------------------------------- */
int date::setDate(int d, int m, int y)
{
if (validDate(d, m, y)) /* 檢查時(shí)間參數(shù)是否合法 */
{
day = d; /* 設(shè)置日期 */
month = m; /* 設(shè)置月份 */
year = y; /* 設(shè)置年份 */
return 1; /* 設(shè)置成功 */
}
else
{
return 0; /* 設(shè)置失敗 */
}
}
/* ---------------------------------------- */
/* 成員函數(shù): 輸出成員資料 */
/* ---------------------------------------- */
void date::printDate()
{
/* 輸出成員資料的月, 日和年 */
cout << month << '-' << day << '-' << year << '\n';
}
/* ---------------------------------------- */
/* 主程式: 使用構(gòu)造函數(shù)建立date對象 */
/* ---------------------------------------- */
void main(){
date birthday; /* 聲明對象 */
/* 使用構(gòu)造函數(shù)聲明對象 */
date yesterday(22, 10, 2001);
cout << "預(yù)設(shè)日期 : ";
birthday.printDate(); /* 使用成員函數(shù)輸出日期 */
birthday.setDate(3,9,1976); /* 使用成員函數(shù)設(shè)置初始值 */
cout << "生日日期 : ";
birthday.printDate(); /* 使用成員函數(shù)輸出日期 */
cout << "昨天日期 : ";
yesterday.printDate(); /* 使用成員函數(shù)輸出日期 */
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -