class (C++)

class關鍵字會宣告類別類型或定義類別類型的物件。

語法

[template-spec]
class [ms-decl-spec] [tag [: base-list ]]
{
   member-list
} [declarators];
[ class ] tag declarators;

參數

template-spec
選擇性樣板規格。 如需詳細資訊,請參閱 範本

class
class 關鍵字。

ms-decl-spec
選擇性儲存類別規格。 如需詳細資訊,請參閱 __declspec 關鍵字。

tag
提供給類別的類型名稱。 標記會變成類別範圍內的保留字。 標記是選擇項。 如果省略,則會定義匿名類別。 如需詳細資訊,請參閱 匿名類別類型

base-list
這個類別從中衍生其成員的選擇性類別或結構清單。 如需詳細資訊, 請參閱 基類。 每個基類或結構名稱前面都可以有存取規範(公用、私人、受保護)和 虛擬 關鍵字。 如需詳細資訊,請參閱控制類別成員 存取中的 成員存取資料表。

member-list
類別成員的清單。 如需詳細資訊, 請參閱類別成員概觀

declarators
宣告子清單,指定類別類型的一個或多個執行個體名稱。 如果 類別的所有資料成員都是 public ,宣告子可能會包含初始化運算式清單。 這在結構中比類別更常見,其資料成員 public 預設為 。 如需詳細資訊, 請參閱 宣告子概觀。

備註

一般來說,如需類別的詳細資訊,請參閱下列其中一個主題:

如需 C++/CLI 和 C++/CX 中 Managed 類別和結構的相關資訊,請參閱 類別和結構

範例

// class.cpp
// compile with: /EHsc
// Example of the class keyword
// Exhibits polymorphism/virtual functions.

#include <iostream>
#include <string>
using namespace std;

class dog
{
public:
   dog()
   {
      _legs = 4;
      _bark = true;
   }

   void setDogSize(string dogSize)
   {
      _dogSize = dogSize;
   }
   virtual void setEars(string type)      // virtual function
   {
      _earType = type;
   }

private:
   string _dogSize, _earType;
   int _legs;
   bool _bark;

};

class breed : public dog
{
public:
   breed( string color, string size)
   {
      _color = color;
      setDogSize(size);
   }

   string getColor()
   {
      return _color;
   }

   // virtual function redefined
   void setEars(string length, string type)
   {
      _earLength = length;
      _earType = type;
   }

protected:
   string _color, _earLength, _earType;
};

int main()
{
   dog mongrel;
   breed labrador("yellow", "large");
   mongrel.setEars("pointy");
   labrador.setEars("long", "floppy");
   cout << "Cody is a " << labrador.getColor() << " labrador" << endl;
}

另請參閱

關鍵字
類別和結構