クラスの基礎

データと処理をまとめる。カプセル化の入門。

概要

クラスは、データ(メンバ変数)と 処理(メンバ関数)をまとめた単位です。 OOP(オブジェクト指向プログラミング)の基盤。

クラスの定義

#include <iostream>
#include <string>

class Person {
public:
    std::string name;
    int age;
    
    // コンストラクタ
    Person(const std::string& n, int a) : name(n), age(a) {}
    
    // メンバ関数
    void greet() {
        std::cout << "こんにちは、" << name << "です。" << std::endl;
    }
    
    int getAge() {
        return age;
    }
};

int main() {
    Person p("太郎", 25);
    p.greet();
    std::cout << "年齢: " << p.getAge() << std::endl;
    
    return 0;
}

こんにちは、太郎です。
年齢: 25

コンストラクタとデストラクタ

#include <iostream>

class Database {
private:
    char* connection;
    
public:
    // コンストラクタ
    Database(const char* name) {
        connection = new char[256];
        snprintf(connection, 256, "接続: %s", name);
        std::cout << connection << std::endl;
    }
    
    // デストラクタ
    ~Database() {
        std::cout << "切断" << std::endl;
        delete[] connection;
    }
};

int main() {
    {
        Database db("mydb");  // コンストラクタ呼び出し
    }  // デストラクタ呼び出し
    
    return 0;
}

接続: mydb
切断

アクセス修飾子:public/private

#include <iostream>

class BankAccount {
private:
    double balance;  // 外部からアクセス不可
    
public:
    BankAccount(double initial) : balance(initial) {}
    
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }
    
    double getBalance() const {
        return balance;
    }
};

int main() {
    BankAccount acc(1000);
    acc.deposit(500);
    std::cout << "残高: " << acc.getBalance() << std::endl;
    
    // acc.balance = 9999;  // エラー! private
    
    return 0;
}

残高: 1500

const メンバ関数

#include <iostream>

class Rectangle {
private:
    double width, height;
    
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    
    // const メンバ関数:メンバを変更しない
    double getArea() const {
        return width * height;
    }
    
    void resize(double w, double h) {
        width = w;
        height = h;
    }
};

int main() {
    const Rectangle r(4, 5);
    std::cout << "面積: " << r.getArea() << std::endl;
    
    // r.resize(3, 3);  // エラー! const オブジェクト
    
    return 0;
}

面積: 20

実践例:計算機クラス

#include <iostream>
#include <cmath>

class Calculator {
public:
    double add(double a, double b) const { return a + b; }
    double subtract(double a, double b) const { return a - b; }
    double multiply(double a, double b) const { return a * b; }
    double divide(double a, double b) const {
        if (b == 0) throw std::invalid_argument("0で割れません");
        return a / b;
    }
};

int main() {
    Calculator calc;
    
    std::cout << "5 + 3 = " << calc.add(5, 3) << std::endl;
    std::cout << "5 * 3 = " << calc.multiply(5, 3) << std::endl;
    
    return 0;
}

5 + 3 = 8
5 * 3 = 15

ポイント

  • クラスはデータと処理をカプセル化
  • コンストラクタ:初期化処理
  • デストラクタ:片付け処理
  • privateでカプセル化
  • constで不変性を明示

まとめ

  • クラス = データ + メソッド
  • コンストラクタ/デストラクタで生命管理
  • アクセス修飾子でカプセル化