注册 登录
编程论坛 C++教室

继承和组合 求9!

ryophoenix 发布于 2008-01-13 20:54, 932 次点击
利用继承和组合两种方式设计日期时间类
继承方式:
class Time{
private:
int hour;
int minite;
int second;
public:
......
};
class DateTime: public Time{
private:
int year;
int month;
int day;
public:
......
};
组合方式:
class Time{
private:
int hour;
int minite;
int second;
public:
......
};
class DateTime{
private:
Time t;
int year;
int month;
int day;
public:
......
};
把类的定义放在单独存放在头文件中, 类的实现用单独的cpp文件, main函数用单独的cpp文件. 以上两种方式都用同一个main:
main(){
DateTime dt1(2008,8,8,19,0,0);
dt1.disp();
dt1.set(2007,8,8,19,0,0);
dt1.disp();
3 回复
#2
忘记喧嚣2008-01-15 22:37
什么问题了???呵呵好奇怪
#3
ryophoenix2008-01-21 01:29


    一个朋友问的   我也搞不清楚   真是~!
#4
lonmaor2008-01-21 10:10
头文件代码
程序代码:
class Time{
private:
    int hour;
    int minute;
    int second;

public:
    Time    (const int& nHour,
            const int& nMinute,
            const int& nSecond);
    Time ();
    void disp();
};

class DateTime: public Time{
private:
    int year;
    int month;
    int day;

public:
    DateTime    (const int& nYear,
                const int& nMonth,
                const int& nDay,
                const int& nHour,
                const int& nMinute,
                const int& nSecond);
    DateTime();
    void disp();
    void set    (const int& nYear,
                const int& nMonth,
                const int& nDay,
                const int& nHour,
                const int& nMinute,
                const int& nSecond);
};
类成员函数实现代码
程序代码:
Time::Time    (const int& nHour,
            const int& nMinute,
            const int& nSecond)
{
    hour = nHour;
    minute = nMinute;
    second = nSecond;
}

Time::Time()
{
    hour = 0;
    minute = 0;
    second = 0;
}
void Time::disp()
{
    cout<<hour<<" Hour(s)"<<endl;
    cout<<minute<<" Minute(s)"<<endl;
    cout<<second<<" Second(s)"<<endl;
}

DateTime::DateTime    (const int& nYear,
                    const int& nMonth,
                    const int& nDay,
                    const int& nHour,
                    const int& nMinute,
                    const int& nSecond)
{
    Time(nHour,nMinute,nSecond);
    day = nDay;
    month = nMonth;
    year = nYear;
}

DateTime::DateTime()
{
    Time();
    year = 0;
    month = 0;
    day = 0;
}

void DateTime::disp()
{
    cout<<year<<" Year(s)"<<endl;
    cout<<month<<" Month(s)"<<endl;
    cout<<day<<" Day(s)"<<endl;
    Time::disp();
}

void DateTime::set (const int& nYear,
                    const int& nMonth,
                    const int& nDay,
                    const int& nHour,
                    const int& nMinute,
                    const int& nSecond)
{
    Time::Time(nHour,nMinute,nSecond);
    day = nDay;
    month = nMonth;
    year = nYear;
}
这里只给出继承类的构造方法。组合类的构造方法请自行完成。
如果加上对时间/日期是否逾界的代码,类的定义就更完善了。
1