/*类的构造函数(1)*/
#include "stdafx.h"
#include <iostream.h>
class Time
{
private:
//私有段
int m_nHour;
int m_nMin;
int m_nSecond;
public:
//公有段
//构造函数无返回值,名称是类名
//进入到构造对象已经存在,无法销毁
Time()
{
init();
cout << this << "This is Construct" << endl;
}
//重载构造函数
Time(int nInitValue)
{
m_nHour = nInitValue;
m_nMin = nInitValue;
m_nSecond = nInitValue;
cout << this << "This is Construct" << endl;
}
//重载构造函数
Time(int nHour, int nMin , int nSecond = 0)
{
m_nHour = nHour;
m_nMin = nMin;
m_nSecond = nSecond;
cout << this << "This is Construct" << endl;
}
//析构函数无参数,无返回值,名称是~类名
~Time()
{
cout << this << "This is DesConstruct" << endl;
}
public:
//各成员函数
int CheckData()
{
if ( (m_nHour >= 0 && m_nHour <= 23) &&
(m_nMin >= 0 && m_nMin <= 59) &&
(m_nSecond >= 0 && m_nSecond <= 59) )
{
return 1;
}
return 0;
}
void init()
{
m_nHour = 0;
m_nMin = 0;
m_nSecond = 0;
}
int GetHour()
{
return m_nHour;
}
int GetMin()
{
return m_nMin;
}
int GetSecond()
{
return m_nSecond;
}
void SetTime(int nHour, int nMin, int nSecond)
{
m_nHour = nHour;
m_nMin = nMin;
m_nSecond = nSecond;
}
void SetTime(int nValue )
{
m_nHour = nValue;
m_nMin = nValue;
m_nSecond = nValue;
}
};
//全局对象最早构造
Time g_Obj;
int main(int argc, char* argv[])
{
//由Time类型实例对象
Time timeobj = 30; //等价与Time timeobj(10)
Time timeobj1; //无参构造
Time timeobj2(11,26); //三参数的构造
cout << "时" << timeobj.GetHour()
<< "分" << timeobj.GetMin()
<< "秒" << timeobj.GetSecond() << endl;
timeobj.SetTime(10,26,10);
cout << "时" << timeobj.GetHour()
<< "分" << timeobj.GetMin()
<< "秒" << timeobj.GetSecond() << endl;
return 0;
}
好了,就写到这,本人学识有限,难免有出错地方,欢迎指正