您的位置:首页 > 其它

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

2015-10-03 11:06 393 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息