利用c++编程时间类的构造函数重载

c++编程时间类的构造函数重载
要求定义一个用时,分,秒计时的时间类Time。在创建time类对象时,可以用不带参数的构造函数将时分秒初始化为0,可以用任意正整数为时分秒赋初值,可以用大于0的任意秒值为time对象赋初值,还可以用"hh:mm:ss"形式的字符串为时分秒赋值

字符串形式的也是通过构造函数吗,代码如下:

#include <iostream>
#include <cstring>
using namespace std;
class Time
{
private:
	int mHour,mMint,mSecond;
public:
	Time(){mHour=0;mMint=0;mSecond=0;}
	Time(int h,int m,int s){mHour=h;mMint=m;mSecond=s;}
	Time(int t)
	{
		mHour = t/3600;
		mMint = t%3600/60;
		mSecond = t%60;
	}
	Time(string s)
	{
		int t = 0;
		int i=0;
		while(s[i]!=':' && s[i]!='\0')
		{
			t = t*10 + s[i]-'0';
			i++;
		}
		mHour = t;
		if(s[i]=='\0')return;
		i++;
		t = 0;
		while(s[i]!=':'&& s[i]!='\0')
		{
			t = t*10 + s[i]-'0';
			i++;
		}
		mMint = t;
		if(s[i]=='\0')return;
		i++;
		t = 0;
		while(s[i] != '\0'&& s[i]!='\0')
		{
			t = t*10 + s[i]-'0';
			i++;
		}
		
		mSecond = t;

	}
	void show()
	{
		cout << mHour<<":"<<mMint<<":"<<mSecond<<endl;
	}
};

int main()
{
	Time t1;
	Time t2(10,2,3);
	Time t3(4000);
	Time t4("2:03:29");
	t1.show();
	t2.show();
	t3.show();
	t4.show();
	return 0;
}

 

img


你题目的解答代码如下:

#include<iostream>
#include<string>
using namespace std;

class Time
{
private:
    int h,m,s;

public:
    Time()
    {
        h = 0;
        m = 0;
        s = 0;
    }
    Time(int th,int tm,int ts)
    {
        h = th;
        m = tm;
        s = ts;
    }
    Time(int ts)
    {
        h = ts / 3600;
        m = ts / 60 % 60;
        s = ts % 60;
    }
    Time(string str)
    {
        h = (str[0]-'0')*10+(str[1]-'0');
        m = (str[3]-'0')*10+(str[4]-'0');
        s = (str[6]-'0')*10+(str[7]-'0');
    }
    void out()
    {
        cout << h << "时 " << m << "分 " << s << "秒" << endl;
    }
};

int main()
{
    Time t1;
    Time t2(8,53,5);
    Time t3(7275);
    Time t4("13:06:57");
    t1.out();
    t2.out();
    t3.out();
    t4.out();
    return 0;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img