const成员函数、inline成员函数、static成员函数中关键字的位置

来源:互联网 发布:阿里云ecs搭建ss 编辑:程序博客网 时间:2024/05/16 08:40

const成员函数

在类中用const修饰成员函数名,

在类外同样需要使用const修改其成员函数名。

否则,编译器会把它看成一个不同的函数。


当然,如果const成员函数直接在类中定义,

类外的声明也就不需要了。

class Player{public:Player(std::string name, int age) : m_strName(name), m_nAge(age){}std::string GetName() const { return m_strName; }int GetAge() const;private:const std::string m_strName;int m_nAge;};int Player::GetAge() const {return m_nAge;}

inline成员函数

如果成员函数直接在类中定义,那么该成员函数直接就是inline成员函数。

使用或者不使用inline对之进行声明效果一样。


如果成员函数的定义在类外进行,那么要使它成为inline函数,

需在它的定义中用inline进行声明,而不是声明中进行声明。


static成员函数

static需要在类申明中进行声明。

如果其定义在类外,类外的定义无需使用static进行声明。

class Player{public:Player() { ++ m_nCnt; }static int GetCnt();private:static int m_nCnt;};int Player::m_nCnt = 0;int Player::GetCnt(){return m_nCnt;}



0 0
原创粉丝点击