类和对象应用例题

用类来实现时间输入输出

#include <iostream>
using namespace std;

class Time{
    public:
        int hour;
        int minute;
        int sec;
};
void set_time(Time&t){ 
    cin>>t.hour;
    cin>>t.minute;
    cin>>t.sec;
}
void show_time(Time&t){
    cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
}
int main(){
    Time t1;
    
    Time t2;
    set_time(t1);
    show_time(t1);
    set_time(t2);
    show_time(t2);
    
    return 0;
}

实参声明

#include <iostream>
using namespace std;

class Time{
    public:
        int hour;
        int minute;
        int sec;
};
void set_time(Time&t,int hour,int minute,int sec){ 
    t.hour=hour;
    t.minute=minute;
    t.sec=sec;
}
void show_time(Time&t){
    cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
}
int main(){
    void set_time(Time&,int hour=0,int nimute=0,int sec=0);
    void show_time(Time&);
    Time t1;
    Time t2;
    set_time(t1,12,23,34);
    show_time(t1);
    set_time(t2);
    show_time(t2);
    
    return 0;
}

标准类的方法

#include <iostream>
using namespace std;

class Time{
    private:
        int hour;
        int minute;
        int sec;
    public:
        void set_time(){
            cin>>hour;
            cin>>minute;m
            cin>>sec;
        }
        void show_time(){
            cout<<hour<<":"<<minute<<":"<<sec<<endl;
        }
};
int main(){
    Time t1;
    Time t2;
    t1.set_time();
    t1.show_time();
    t2.set_time();
    t2.show_time();
    return 0;
}

 

posted @ 2017-12-22 09:11  Advancing-Swift  阅读(347)  评论(0编辑  收藏  举报