LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 158|回复: 0

成员函数概述

[复制链接]
发表于 2024-2-2 23:17:39 | 显示全部楼层 |阅读模式
成员函数是静态或非静态的。 静态成员函数的行为与其他成员函数的行为不同,因为静态成员函数不具有隐式 this 参数。 非静态成员函数具有 this 指针。 可以在类声明的内部或外部定义成员函数(无论是静态的还是非静态的)。

如果在类声明的内部定义一个成员函数,则该函数会被视为内联函数,并且不需要用其类名来限定函数名称。 尽管已将类声明中定义的函数视为内联函数,但你可以使用 inline 关键字来记录代码。

在类声明中声明函数的示例如下所示:

// overview_of_member_functions1.cpp
class Account
{
public:
    // Declare the member function Deposit within the declaration
    //  of class Account.
    double Deposit( double HowMuch )
    {
        balance += HowMuch;
        return balance;
    }
private:
    double balance;
};

int main()
{
}
如果成员函数的定义在类声明的外部,则仅在将该函数显式声明为 inline 时才将其视为内联函数。 此外,必须通过范围解析运算符 (: 用类名称限定定义中的函数名称。

以下示例与类 Account 的以前的声明等效,只不过 Deposit 函数是在类声明的外部定义的:

// overview_of_member_functions2.cpp
class Account
{
public:
    // Declare the member function Deposit but do not define it.
    double Deposit( double HowMuch );
private:
    double balance;
};

inline double Account:eposit( double HowMuch )
{
    balance += HowMuch;
    return balance;
}

int main()
{
}

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表