类的深入剖析

简单的Time类

Time.h

//使用预处理命令可以防止出现重复性错误,习惯上,预处理中包含的符号常量通常是大写的头文件名,并用下划线替换句点
#ifndef TIME_H
#define TIME_H
class Time{
public:
    Time();
    void setTime(int, int, int);
    void printUniversal();
    void printStandard();
private:
    int hour;
    int minute;
    int second;
};
#endif

Time.cpp    //类Time成员函数的定义

#include<iostream>
#include<iomanip>
#include"Time.h"
using namespace std;
Time::Time(){
    hour = minute = second = 0;
}
void Time::setTime(int h, int m, int s){
    hour = (h >= 0 && h < 24) ? h : 0;
    minute = (m >= 0 && m < 60) ? m : 0;
    second = (s >= 0 && s < 60) ? s : 0;
}
void Time::printUniversal(){//当地时间
    cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second;
}
void Time::printStandard(){//标准时间
    cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":"
    << setfill('0') << setw(2) << minute << ":" << setw(2) << second << (hour < 12 ? "AM" : "PM");
}

//测试Time类

#include<iostream>
#include"Time.h"
using namespace std;
int main(){
    Time t;
    cout << "The initial universe time is ";
    t.printUniversal();
    cout << "\nThe initial standard time is ";
    t.printStandard();

    t.setTime(13, 27, 6);
    cout << "\n\n\n Universal time after set time is :";
    t.printUniversal();
    cout << "\n\n\n Standard time after set time is :";
    t.printStandard();

    t.setTime(99, 99, 99);
    cout << "\n\n\n Universal time after set time is :";
    t.printUniversal();
    cout << "\n\n\n Standard time after set time is :";
    t.printStandard();
    cout << endl;
}

类域和访问类的成员

类的数据成员(类定义中声明的变量)和成员函数(类定义中声明的函数)属于该类的类域。非成员函数在全局命名域内定义。

在类域中,类的成员可以被该类的所有成员函数直接访问,并且可以按照名字引用。

在类域外,通过对象的句柄,对象名、对象的引用、指向对象的指针之一引用public类型的类成员。

类的成员函数只能被该类的其他成员函数所重载。重载成员函数只需要在类定义中提供重载函数各个版本的原型,并为该函数的各个版本提供不同的函数定义。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小菜鸡变形记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值