classについて【C++】
C++におけるstructとclassの違い
- structとはC言語においてデータ構造を定義するための機能です。
- classはstructに関数が定義できるようになったもの。
- C言語では必要だったtypedefがC++では不要。
- structは、デフォルトのアクセシビリティがpublic
- classは、デフォルトのアクセシビリティがprivate
- アクセス指定はprivate、protected、publicの3種類。
- POD(Plain Old Data)型のデータ構造(C言語と互換性のあるデータ構造)を定義する時以外はクラスを使うのが推奨される?
テストコード
class person{ //アクセシビリティ(private) public://以下、public int id; int age; string name; // print information void print(){ cout << "id :" << id << endl; cout << "age :" << age << endl; cout << "name:" << name << endl; } }; int main(){ person kobayashi = {0, 14, "kobayashi"}; kobayashi.print(); }
実行結果
id :0 age :14 name:kobayashi