共用方式為


類別成員概觀

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 };

成員存取範圍

成員清單中所宣告類別的成員。 類別的成員清單可分成任意數目的 privateprotected 以及 public 使用稱為存取規範的關鍵字區段。 冒號 : 必須遵循存取規範。 這些區段不需要連續;也就是說,這些關鍵字中的任何一個可能會出現在成員清單中數次。 關鍵字會指定到下一個存取指定名稱,或右大括號之前所有成員的存取權限。 如需詳細資訊,請參閱 成員存取控制(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 類別的成員。

另請參閱

類別和結構