クラス (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 のクラスでは構造体で共通です。詳細については、「宣言の概要」を参照してください。
解説
通常クラスの詳細については" " の 1 を参照します :
マネージ クラスと構造体の詳細についてはクラスと構造体 を参照してください。
使用例
// class.cpp
// compile with: /EHsc
// Example of the class keyword
// Exhibits polymorphism/virtual functions.
#include <iostream>
#include <string>
#define TRUE = 1
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;
}