类成员概述

classstruct 由其成员组成。 类的工作由其成员函数执行。 它所维持的状态存储在其数据成员中。 成员的初始化由构造函数完成,释放内存和释放资源等清理工作由析构函数完成。 在 C++ 11 和更高版本中,数据成员可以(并且通常应该)在声明时初始化。

类成员的种类

成员类别的完整列表如下:

类声明示例

下面的示例显示了一个简单的类声明:

// TestRun.h

class TestRun
{
    // Start member list.

    // The class interface accessible to all callers.
public:
    // Use compiler-generated default constructor:
    TestRun() = default;
    // Don't generate a copy constructor:
    TestRun(const TestRun&) = delete;
    TestRun(std::string name);
    void DoSomething();
    int Calculate(int a, double d);
    virtual ~TestRun();
    enum class State { Active, Suspended };

    // Accessible to this class and derived classes only.
protected:
    virtual void Initialize();
    virtual void Suspend();
    State GetState();

    // Accessible to this class only.
private:
    // Default brace-initialization of instance members:
    State _state{ State::Suspended };
    std::string _testName{ "" };
    int _index{ 0 };

    // Non-const static member:
    static int _instances;
    // End member list.
};

// Define and initialize static member.
int TestRun::_instances{ 0 };

成员可访问性

在成员列表中声明类的成员。 可使用称为访问说明符的关键字将类的成员列表分为任意数量的 privateprotectedpublic 部分。 冒号 : 必须跟在访问说明符后面。 这些部分不需要是连续的,也就是说,这些关键字中的任何一个都可能在成员列表中多次出现。 关键字指定所有成员直到下一个访问说明符或右大括号的访问。 有关详细信息,请参阅成员访问控制 (C++)

静态成员

可将数据成员声明为静态,这表示类的所有对象都有权访问它的同一副本。 可将成员函数声明为静态,在这种情况下它只能访问类的静态数据成员(且不具有 this 指针)。 有关详细信息,请参阅静态数据成员

特殊成员函数

如果未在源代码中指定特殊成员函数,那么编译器自动提供的函数则为特殊成员函数。

  • 默认构造函数

  • 复制构造函数

  • (C++11) 移动构造函数

  • 复制赋值运算符

  • (C++11) 移动赋值运算符

  • 析构函数

有关详细信息,请参阅特殊成员函数

按成员初始化

在 C++ 11 和更高版本中,非静态成员声明符可以包含初始值设定项。

class CanInit
{
public:
    long num {7};       // OK in C++11
    int k = 9;          // OK in C++11
    static int i = 9; // Error: must be defined and initialized
                      // outside of class declaration.

    // initializes num to 7 and k to 9
    CanInit(){}

    // overwrites original initialized value of num:
    CanInit(int val) : num(val) {}
};
int main()
{
}

如果在构造函数中对成员赋值,则该值将覆盖声明时指定的值。

对于给定类类型的所有对象,只有一个静态数据成员的共享副本。 必须在文件范围内定义静态数据成员并可在此范围内将其初始化。 有关静态数据成员的详细信息,请参阅静态数据成员。 以下示例演示如何使用静态数据成员:

// class_members2.cpp
class CanInit2
{
public:
    CanInit2() {} // Initializes num to 7 when new objects of type
                 //  CanInit are created.
    long     num {7};
    static int i;
    static int j;
};

// At file scope:

// i is defined at file scope and initialized to 15.
// The initializer is evaluated in the scope of CanInit.
int CanInit2::i = 15;

// The right side of the initializer is in the scope
// of the object being initialized
int CanInit2::j = i;

注意

类名 CanInit2 的前面必须有 i 以指定所定义的 i 是类 CanInit2 的成员。

另请参阅

类和结构