对外接口Set,可以限制非法时间值

发布时间 2023-04-20 23:30:49作者: PeitongShi

类作为"零件"的载体,有内部属性(private),有对外接口(public), 内部属性的数据成员或函数成员,仅仅供给class内部函数成员使用,不对外开放,public规定的对外开放的接口。

设置Cmytime类。

具有两个成员函数

int Set(int h,int m,int s)

对于Set函数的要求,

     1、对于非法赋值不给予执行,三个参数合法范围是:0<=h<=23,  0<=m,s<=59。 如何参数非法,本次Set函数不改变原有值。

    2、赋值成功,返回1,否则返回0。

Show()

输入  23  25 38

输出:  23:25:38

#include<iostream>
using namespace std;
class Cmytime
{
private://内部属性 
    int hour,minute,second; 
public://对外接口 
    int Set(int h,int m,int s)
    {
        if(((h>=0)&&(h<=23))&&(m>=0)&&(s<=59))
        {
            hour=h;
            minute=m;
            second=s;
            return 1; 
        }
        else
        {
            return 0;
        }
    }
    void Show()
    {
        cout << hour << ":" << minute << ":" << second;
    }
};
//StudybarCommentBegin
int main(void) {
    int h,m,s;
   cin>>h>>m>>s;
  Cmytime t1;
t1.Set(1,2,3);
t1.Set(h,m,s);
t1.Show();
    return 0;
}

//StudybarCommentEnd

-END