1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑯~クラス~

Last updated at Posted at 2022-07-12

クラス

クラスとは、新しいデータ型を作るための仕組み
データ機能をまとめて定義することができる
classを用いて書く

structとの違い

C++におけるstructclass1点だけ

デフォルトのアクセス指定子の違い

  • classはデフォルトのアクセス指定子がprivate
  • structはデフォルトのアクセス指定子がpublic

アクセス指定子

アクセス指定子とは、データや関数などへのアクセス許可の範囲のこと
メンバーをprivateとした場合、クラスの外部からは、そのクラスのそのメンバーを参照する事ができない

クラスの構文

クラスの宣言

class クラス名{
  アクセス指定子:
    1 メンバ変数名1
    2 メンバ変数名2
    ...
    戻り値の型1 メンバ関数名1
}

クラスの呼び出し

クラス名 オブジェクト名;
オブジェクト名.メンバ変数 = メンバ変数に設定する値
オブジェクト名.メンバ関数;

クラスを用いたプログラム

#include <iostream>
using namespace std;
 
class Aisatsu {
  public:
    string japanese;
    string english;
    void speak(){
      cout << japanese << endl;
      cout << english << endl;
    }
};
 
int main() {
  Aisatsu aisatsu;
  aisatsu.japanese = "こんにちは";
  aisatsu.english = "Hello";
  aisatsu.speak();
}
こんにちは
Hello

メンバ関数の定義について

メンバ関数の定義の仕方は2つある

  1. クラスの内部で作る方法
  2. クラスの外部で作る方法

関数の処理が長くなると可読性が悪くなるので、クラスの外部で定義することが多い

関数を外部で作成する構文

スコープ解決演算子::を使う

戻り値の型 クラス名::メンバ関数名{
  // 処理
}

外部で関数を定義したプログラム

#include <iostream>
using namespace std;
 
class Aisatsu {
  public:
    string japanese;
    string english;
    void speak();
};

void Aisatsu::speak(){
  cout << japanese << endl;
  cout << english << endl;
}

int main() {
  Aisatsu aisatsu;
  aisatsu.japanese = "こんにちは";
  aisatsu.english = "Hello";
  aisatsu.speak();
}
こんにちは
Hello

次の記事

【C++】基礎を学ぶ⑰~カプセル化~

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?