1_类的定义(Defining Class)

  C++ 提供了一种类class机制,让程序员可以定义真正意义上的数据类型。即不但可以定义数据的复合,还可以定义该复合数据的操作,以便让本应由使用该数据类型的程序员做得工作分出来,让定义类型的程序员去做。类机制定义类class,类是一种类型type。定义类的格式与struct相像,只是在定义体内添加操作(即函数)。以下以一个日期类型的定义来描述。

//=============================================
//日期类应用程序
//=============================================

#include <iostream>
#include <iomanip>

using namespace std;

/**
*类定义体
*/
class Date{
private:
    int year,month,day;
public:
    void set(int y,int m,int d);
    bool isLeapYear();
    void print();
};

//成员函数类定义体外定义
void Date::set(int y,int m,int d)
{
    year = y;
    month = m;
    day = d;
}

bool Date::isLeapYear()
{
    return (year%4==0 && year%100!=0)||(year%400==0);
}

void Date::print()
{
    cout<<setfill('0');
    cout<<setw(4)<<year<<'-'<<setw(2)<<month<<'-'<<setw(2)<<day<<'
';
    cout<<setfill(' ');
}

//使用日期类
int main()
{
    Date d;
    d.set(2000,12,36);
    if(d.isLeapYear())
    {
        d.print();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/houjun/p/8423047.html