运行结果:
代码:
#include <iostream>
using namespace std;
class Time
{
//属性
private:
int hour; //时
int mint; //分
int second; //秒
public:
//构造函数
Time(int h = 0, int m = 0, int s = 0) {
cout << "构造函数调用" << endl;
hour = h; mint = m; second = s;
}
//拷贝构造函数
Time(Time& t) {
cout << "拷贝构造函数调用" << endl;
hour = t.hour; mint = t.mint; second = t.second;
}
//增改函数
void setHour(int h) {
if (hour < 24)
hour = h;
else
cout << "小时必须小于24" << endl;
} //设置时间
int getHour() { return hour; } //获取时间
void setMint(int m) {
if (m < 60)
mint = m;
else
cout << "分钟必须小于60" << endl;
} //设置分钟
int getMint() { return mint; } //获取分钟
void setSecond(int s) {
if (s < 60)
second = s;
else
cout << "秒必须小于60" << endl;
} //设置秒
int getSecond() { return second; } //获取秒
//增加函数1 ,通过输入时分秒增加,这里要求小时<24,分钟和秒数<60
void add(int h, int m, int s)
{
//计算秒
second += s;
if (second >= 60)
{
second -= 60;
mint += 1; //分钟+1
}
//计算分钟
mint += m;
if (mint >= 60)
{
mint -= 60;
hour += 1;
}
//计算时
hour += h;
if (hour >= 24)
hour -= 24;
}
//增加函数2,只输入秒数
void addSecond(int s)
{
int h, m, sec;
sec = s % 60; //剩余秒数
h = s / 3600; //得到小时数
m = (s - h * 3600) / 60; //得到分钟数
add(h, m, sec);
}
//增加函数3,只输入分钟
void addMint(int m)
{
int sec = m * 60;
addSecond(sec);
}
//增加函数4,只输入小时
void addHour(int h)
{
int sec = h * 3600;
addSecond(sec);
}
};
int main()
{
Time t(10, 2, 23); //调用构造函数
cout << "t:";
cout << t.getHour() << ":" << t.getMint() << ":" << t.getSecond() << endl;
cout << "用t构建t2:" << endl;
Time t2(t); //调用拷贝构造函数
cout << "t2:";
cout << t2.getHour() << ":" << t2.getMint() << ":" << t2.getSecond() << endl;
cout << "请输入t2的时 分 秒,以修改t2 (空格分隔)";
int h, m, s;
cin >> h >> m >> s;
t2.setHour(h);
t2.setMint(m);
t2.setSecond(s);
cout << "修改后t2:";
cout << t2.getHour() << ":" << t2.getMint() << ":" << t2.getSecond() << endl;
cout << "在t的基础上增加一段时间后,计算新时间,请输入需要增加的时 分 秒:";
cin >> h >> m >> s;
t.add(h, m, s);
cout << "在t的基础上增加" << h << "小时" << m << "分钟" << s << "秒后的新时间:";
cout << t.getHour() << ":" << t.getMint() << ":" << t.getSecond() << endl;
return 0;
}
class Time
{
public:
int Hour;
int Minute;
int Second;
Time(int h, int m, int s) : Hour(h), Minute(m), Second(s) { }
Time(Time &t) { Hour = t.Hour; Minute = t.Minute; Second = t.Second; }
void SetTime(int h, int m, int s) { Hour = h; Minute = m; Second = s; }
void AddSeconds(int s)
{
int totalSeconds = Hour * 3600 + Minute * 60 + Second + s;
if (totalSeconds < 0)
{
totalSeconds += 86400; //一天86400秒
}
Hour = (totalSeconds / 3600) % 24;
Minute = (totalSeconds % 3600) / 60;
Second = totalSeconds % 60;
}
void AddMinutes(int m)
{
AddSeconds(m * 60);
}
void AddHours(int h)
{
AddSeconds(h * 3600);
}
};
#include <cmath>
using namespace std;
class Point
{
public:
Point()
{
cout<<"无参构造函数"<<endl;
}
Point(int a)
{
cout<<"有参构造函数"<<endl;
}
~Point()
{
cout<<"析构函数"<<endl;
}
};
void test()
{
Point p1;
Point p2(10);
}
int main()
{
test();
return 0;
}
输出:
默认构造函数就是没有带明显形参或提供了默认实参的构造函数,可以等价为无参构造函数。