2_成员函数(Member Functions)

  成员函数以定从属于类,不能独立存在,这是它与普通函数的重要区别。所以我们在类定义体外定义成员函数的时候,必须在函数名之前冠以类名,如Date::isLeapYear()。但如果在类定义体内定义成员函数时,并不需要在成员函数前冠以类名。

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

#include <iostream>
#include <iomanip>

using namespace std;

/**
*类定义体
*/
class Date{
private:
    int year,month,day;
public:
    //在类定义体内定义成员函数,不需要在函数名前冠以类名
    void set(int y,int m,int d)
    {
        year = y;
        month = m;
        day = d;
    };
    bool isLeapYear();
    void print();
};

//成员函数类定义体外定义

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(' ');
}

  需要注意的是,函数定义的花括号后面没有分号,而类定义的花括号后面以定由分号,这是由于C语言的历史原因造成的。class机制是建立在struct机制之上,所以要和struct对应。

  在类内定义的成员函数,就默认声明内联函数的性质,因此当代码量较小,不超过3行的成员函数,放在类中定义比较合适。同样,我们也可以在类外定义成员函数,对编译提出内联要求。

代码如下:

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

#include <iostream>
#include <iomanip>

using namespace std;

/**
*类定义体
*/
class Date{
private:
    int year,month,day;
public:
    //在类定义体内定义成员函数,不需要在函数名前冠以类名
    void set(int y,int m,int d)
    {
        year = y;
        month = m;
        day = d;
    };
    bool isLeapYear();
    void print();
};

//成员函数类定义体外定义

inline 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(' ');
}
原文地址:https://www.cnblogs.com/houjun/p/8423115.html