0
0

[初級] C++: クラスの基本

Posted at

C++ のクラスの基礎の基礎
class

本記事の前提条件は以下の通りです。

  • 初心者向け
  • とは言っても、何らかのプログラムはそれなりに書けるけど、C とか C++ はちょっと、という人向け
  • ざっくり概要しか説明しないので細かいことは気にしないでいただきたい
  • Visual Studio 2013 くらい~
  • Windowsプログラム (CUI, GUI)
  • コードの検証
    • 開発環境: Visual Studio 2022, x64, Release ビルド
    • 実行環境: Windows 10
  • 本記事は上から順番に読む前提となっている
  • 「Windowsプログラム (CUI, GUI)」と書いてあるが、本記事の内容だとどの OS でもほぼ同じ

クラスとは

ざっくり言うと、データと、関連する処理をまとめたものである。

例えば足し算をする場合、クラスを使わないとこのようになる。

int Add(int augend, int addend)
{
    return augend + addend;
}
int Subtract(int minuend, int subtrahend)
{
    return minuend - subtrahend;
}

int value = 0;
// -> value: 0
value = Add(value, 3);
// -> value: 3
value = Subtract(value, 1);
// -> value: 2

クラスを使うとこのようになる。

class IntCalc
{
public:
    int value = 0;
    void Add(int addend)
    {
        value += addend;
    }
    void Subtract(int subtrahend)
    {
        value -= subtrahend;
    }
};

IntCalc calc;
// -> calc.value: 0
calc.Add(3);
// -> calc.value: 3
calc.Subtract(1);
// -> calc.value: 2

データ (value) と処理 (Add, Subtract) の関係がすっきりした。
引数も減ったし、戻り値もなくなったのでコーディングミスも少なくなりそうだ。

以上!

0
0
0

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
0
0