内联类成员函数
类声明的主体中定义的函数是内联函数。
示例
在下面的类声明中,Account 构造函数是内联函数。 成员函数 GetBalance、Deposit 和 Withdraw 未指定为“内联”,但可作为内联函数实现。
// Inline_Member_Functions.cpp
class Account
{
public:
Account(double initial_balance) { balance = initial_balance; }
double GetBalance();
double Deposit( double Amount );
double Withdraw( double Amount );
private:
double balance;
};
inline double Account::GetBalance()
{
return balance;
}
inline double Account::Deposit( double Amount )
{
return ( balance += Amount );
}
inline double Account::Withdraw( double Amount )
{
return ( balance -= Amount );
}
int main()
{
}
备注
在类声明中,声明函数而无需 inline 关键字。inline 关键字可以在类声明中指定;结果也相同。
给定的内联成员函数在每个编译单元中必须以相同的方式进行声明。 此约束会导致内联函数像实例化函数一样运行。 此外,必须有精确的内联函数的定义。
除非该函数的定义包含“内联”说明符,否则类成员函数默认为外部链接。 前面的示例说明这些函数不需要用“内联”说明符进行显式声明;在函数定义中使用“内联”会导致它成为一个内联函数。 但是,在调用该函数后,重新将该函数声明为“内联”是非法的。