1. クラスの定義
オブジェクト指向プログラミングにおいて、クラスはオブジェクトの構造と振る舞いを定義する基本要素です。C++では、クラスは名前、データメンバー(プロパティ)、およびメンバ関数(メソッド)で構成されます。データメンバーはオブジェクトの状態を保持し、メンバ関数はそのオブジェクトが実行可能な操作を定義します。
1.1 クラス名
C++ではclassキーワードでクラスを定義します。クラス名は通常、先頭を大文字とするキャメルケースで命名されます。
例として、以下に示すRectangleクラスがあります。
1.2 アクセス修飾子
C++では、クラス内部のメンバーに対するアクセスを制御するために、次の3つの修飾子があります。
public: クラス外部からアクセス可能protected: 派生クラスからのみアクセス可能private: クラス内部でのみアクセス可能
アクセス修飾子の効力は、次に別の修飾子が現れるまで、またはクラス定義の終わりまで続きます。
例1: Rectangleクラス
#include <iostream>
using namespace std;
class Rectangle {
private:
int width;
int height;
public:
Rectangle(int w = 0, int h = 0) : width(w), height(h) {}
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
int getArea() const {
return width * height;
}
};
int main() {
Rectangle rect(3, 4);
cout << "Area: " << rect.getArea() << endl;
return 0;
}
1.3 クラススコープ
クラスのスコープは、左波括弧{から右波括弧}までの範囲で定義されたすべてのメンバーを含みます。このスコープ内でのメンバーの可視性は、アクセス修飾子によって制御されます。
例2: Personクラス
class Person {
public:
void display() {
cout << name << ", " << age << endl;
}
private:
string name;
int age;
};
int main() {
Person p;
p.name = "John"; // コンパイルエラー: nameはprivate
p.display(); // OK: publicメソッドを通じてアクセス
return 0;
}
2. オブジェクトのインスタンス化
2.1 インスタンス化の概念
クラスは設計図であり、その設計図に基づいて複数のオブジェクトを生成することができます。この生成過程をインスタンス化といいます。
例3: Pointクラスのインスタンス化
class Point {
private:
int x, y;
public:
Point(int x_val = 0, int y_val = 0) : x(x_val), y(y_val) {}
void print() const {
cout << "(" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p1(10, 20);
Point p2;
p1.print(); // (10, 20)
p2.print(); // (0, 0)
return 0;
}
2.2 オブジェクトのサイズ
クラスのサイズは、そのデータメンバーの型、配置、アラインメントによって決まります。メンバ関数自体は通常、オブジェクトのサイズには含まれません。
例4: MyClassのサイズ
class MyClass {
public:
char a;
int b;
double c;
};
int main() {
cout << "Size of MyClass: " << sizeof(MyClass) << " bytes" << endl;
return 0;
}
この例では、MyClassのサイズは16バイトになります。
例5: メンバ関数のサイズ影響
class Empty {
public:
void dummy() {}
};
int main() {
cout << "Size of Empty: " << sizeof(Empty) << " bytes" << endl;
return 0;
}
空のクラスであっても、サイズは1バイトになります。これはオブジェクトの存在を示すためです。
3. thisポインタ
C++では、すべての非staticメンバ関数に暗黙的にthisポインタが追加されます。このポインタは、呼び出し元のオブジェクトへの参照を保持します。
例6: thisポインタの使用
class Box {
private:
double width;
public:
void setWidth(double width) {
this->width = width;
}
double getWidth() const {
return width;
}
};
int main() {
Box box;
box.setWidth(5.0);
cout << "Width: " << box.getWidth() << endl;
return 0;
}