慣例上代碼:
第一個是.h文件
#include<iostream>
#include<iomanip>
using namespace std;
#ifndef MY_H_FILE //如果沒有定義這個宏
#define MY_H_FILE //定義這個宏
class data_X
{
public:
data_X(int, int);
void setX(int);
void setData(int);
int getData();
private:
int data;
int X;
};
data_X::data_X(int x, int Data = 0)
{
setX(x);
setData(Data);
}
inline void data_X::setX(int x)
{
if (x == 0)
{
cout << "0 is invalid." << endl;
}
else
{
X = x;
}
}
inline void data_X::setData(int Data)
{
if (Data >= 0 && Data <= X)
{
data = Data;
}
else
{
cout << "data is invalid." << endl;
}
}
inline int data_X::getData()
{
return data;
}
class Hour :public data_X
{
public:
Hour(int iHour = 0) :data_X(12, iHour)
{}
};
class Minute :public data_X
{
public:
Minute(int iMinute = 0) :data_X(60, iMinute)
{}
};
class Second :public data_X
{
public:
Second(int iSecond = 0) :data_X(60, iSecond)
{}
};
class Time
{
public:
Time(int, int, int);
void display();
private:
Hour hour;
Minute minute;
Second second;
};
Time::Time(int iHour, int iMinute, int iSecond)
{
hour = Hour(iHour);
minute = Minute(iMinute);
second = Second(iSecond);
}
void Time::display()
{
cout << setfill('0') << setw(2) << hour.getData() << ":" << minute.getData() << ":" << second.getData() << endl;
}
#endif
還有一個cpp文件:
#include"TimeAndDate.h"
int main()
{
Time currentTime(20, 16, 13);
currentTime.display();
}
如果你程序只有這兩個文件的話,按理說沒有錯。我親自測試了
建議你把bin obj刪除了重新編譯一下看看。