404 Not Found

404 Not Found


nginx

C++のクラス

[前のレッスンでは]、[私たちは]struct[を使って、異なる]型[の]変数[を1つの単位としてまとめました]。

[しかし、現実世界の事物には][属性]([名前]、[年齢]など)だけでなく、[行動]([歩く]、[話す]など)も[ある]。

クラス[とは、]「[事物]」[を]記述するためのもの――[それは][属性][と][振る舞い]をカプセル化[する]ものである。


1. クラスとは何ですか?

(1) 1.1 [生活の中の]クラス

[生活シーン] 番組[での対応]
[建築設計図]([建物の構造が記載されている]) class([物事を記述する]テンプレート)
[図面に基づいて建てられた家]([実際の物体]) object(class[の]インスタンス)

クラスとオブジェクト:

(2) 1.2 なぜクラスが必要なのか?

[不要]class([必要]struct,[制限あり]):

CPP
#include iostream
#include string

struct Student {
 std::string name;
 int age;
 double score;
};

int main() {
 Student s1 = {"Alice", 20, 92.5};
 // ❌ "..."("...")
 return 0;
}

[用]クラス([完全]):

CPP
#include iostream
#include string

class Student {
public:
 std::string name;
 int age;
 double score;
 
 void introduce() {
 std::cout << "My name is" << name << ",I'm" << age << "years old。" << std::endl;
 }
};

int main() {
 Student s1;
 s1.name = "Alice";
 s1.age = 20;
 s1.introduce(); // ✅ "..."
 return 0;
}


2. class[の定義]*

(1) 2.1 [基本構文]

CPP
class {
public:
 // ()
};

💡 [ポイント]: クラス[の定義は][セミコロン][で終わる]!([struct][と同様に])

▶ サンプル 1: [定義] Student クラス (難易度 ⭐)

CPP
#include iostream
#include string

class Student {
public:
 // ()
 std::string name;
 int age;
 double score;
 
 // ()
 void introduce() {
 std::cout << "My name is" << name << ",I'm" << age << "years old。" << std::endl;
 }
 
 void study() {
 std::cout << name << "..." << std::endl;
 }
};

int main() {
 Student s1;
 s1.name = "Alice";
 s1.age = 20;
 s1.score = 92.5;
 
 s1.introduce();
 s1.study();
 
 return 0;
}
▶ 試してみよう

出力:

TEXT
 Alice, 20。
Alice ...


3. [アクセス権限の管理]*

C++のクラスには、public([パブリック])、private([プライベート])、protected([プロテクト])の3つのアクセス権限があります。

(1) 3.1 パブリックとプライベート*

[権限] class[外部からアクセス可能か]? [用途]
public ✅ [能] [対外]インターフェース([外部から利用可能])
非公開 ❌ [不可] [内部実装]([詳細を非表示])

例:

CPP
#include iostream
#include string

class Student {
private:
 std::string name; // ...
 int age;
 
public:
 // setter getter
 void setName(const std::string& n) {
 name = n;
 }
 
 std::string getName() {
 return name;
 }
};

int main() {
 Student s1;
 // s1.name = "Alice"; // ❌:name Yes's
 s1.setName("Alice"); // ✅ Yes
 std::cout << s1.getName() << std::endl;
 return 0;
}

💡 カプセル化[概念]: [属性を] private に設定し、public [の] setter/getter [を通じて] アクセスする――[これにより、アクセスロジックを制御できる]([例えば、年齢が負の数値ではないかを確認するなど])。



4. コンストラクタ(Constructor)*

(1) 4.1 コンストラクタとは何か?

コンストラクタ[とは]クラス[に含まれる特別な]関数であり、[オブジェクトを]作成[する際に自動的に呼び出される]ものです。

[特徴] [説明]
関数名 [和]クラス[名と同じ]
[戻り値なし] [連] void [何も書かない]
[自動呼び出し] [オブジェクト作成時に自動実行]

▶ サンプル 2: [定義]コンストラクタ (難易度 ⭐⭐)

CPP
#include iostream
#include string

class Student {
private:
 std::string name;
 int age;
 
public:
 // ...
 Student(const std::string& n, int a) {
 name = n;
 age = a;
 std::cout << "Student:" << name << std::endl;
 }
 
 void introduce() {
 std::cout << "My name is" << name << ",I'm" << age << "years old。" << std::endl;
 }
};

int main() {
 Student s1("Alice", 20); // ✅ callingconstructor
 s1.introduce();
 
 return 0;
}
▶ 試してみよう

出力:

TEXT
Student:Alice
 Alice, 20。


5. デストラクタ(Destructor)*

(1) 5.1 デストラクタとは何か?

デストラクタ[は]クラス[に含まれるもう一つの特別な]関数であり、オブジェクト[が破棄される際に自動的に呼び出される]ものです([例えば]関数が[終了したとき]や、delete [が実行されたとき]など)。

[特徴] [説明]
関数名 ~class[名]
[戻り値なし] [連] void [何も書かない]
[引数なし] [引数を受け付けない]
[自動呼び出し] オブジェクト[破棄時に自動的に実行される]

▶ サンプル 3: [定義]デストラクタ (難易度 ⭐⭐)

CPP
#include iostream
#include string

class Student {
private:
 std::string name;
 
public:
 // ...
 Student(const std::string& n) {
 name = n;
 std::cout << ":" << name << "..." << std::endl;
 }
 
 // ...
 ~Student() {
 std::cout << ":" << name << "..." << std::endl;
 }
};

int main() {
 Student s1("Alice"); // ...
 // main,s1,callingdestructor
 return 0;
}
▶ 試してみよう

出力:

💡 [用途]: [デストラクタ内でリソースを解放する]([fileの閉じたり]、[動的メモリを解放したり]など)。



6. このポインタ*

(1) 6.1 このポインタとは何ですか?

this [は][現在の]オブジェクト[を指す]ポインタ——[メンバ関数][内では]、this [を使って現在の]オブジェクト[にアクセスできる]。

▶ サンプル 4: [用] this [区分同名パラメータ] (難易度 ⭐⭐)

CPP
#include iostream
#include string

class Student {
private:
 std::string name;
 
public:
 void setName(const std::string& name) { // ⚠️ and
 this->name = name; // ✅ Using this->
 }
 
 std::string getName() {
 return this->name; // ✅ this-> ()
 }
};

int main() {
 Student s1;
 s1.setName("Alice");
 std::cout << s1.getName() << std::endl;
 return 0;
}
▶ 試してみよう

💡 [ヒント]: [パラメータ名と]メンバー変数名[が異なる場合]、this->は[省略してもよい]([省略することを推奨]、コードが[より簡潔]になる)。



7. 演習:[簡単な銀行口座]クラス*

▶ サンプル 5: BankAccount クラス (難易度 ⭐⭐⭐)

CPP
#include iostream
#include string
#include iomanip

class BankAccount {
private:
 std::string owner;
 double balance;
 
public:
 // ...
 BankAccount(const std::string& o, double initialBalance) {
 owner = o;
 if (initialBalance >= 0) {
 balance = initialBalance;
 } else {
 balance = 0.0;
 std::cout << "⚠️, 0" << std::endl;
 }
 }
 
 // ...
 void deposit(double amount) {
 if (amount > 0) {
 balance += amount;
 std::cout << "!+" << amount << std::endl;
 } else {
 std::cout << "⚠️ 0" << std::endl;
 }
 }
 
 // ...
 void withdraw(double amount) {
 if (amount > 0 && amount <= balance) {
 balance -= amount;
 std::cout << "!-" << amount << std::endl;
 } else if (amount <= 0) {
 std::cout << "⚠️ 0" << std::endl;
 } else {
 std::cout << "⚠️" << std::endl;
 }
 }
 
 // ...
 void queryBalance() {
 std::cout << std::fixed << std::setprecision(2);
 std::cout << ":" << balance << "..." << std::endl;
 }
};

int main() {
 BankAccount account("MOTO", 1000.0);
 
 account.queryBalance();
 account.deposit(500.0);
 account.queryBalance();
 account.withdraw(200.0);
 account.queryBalance();
 account.withdraw(2000.0); // ...
 
 return 0;
}
▶ 試してみよう

[動作結果]:

⚠️ 

❓ よくある質問

Q コンストラクタは[オーバーロード][できますか]?
A [できます]![複数の]コンストラクタ([引数が異なるもの])を定義できます。

📖 まとめ


📝 練習問題

  1. 初心者(難易度 ⭐): Bookというクラスを定義し、[書名]、[著者]、[価格]の3つのプライベートメンバーを含める。
  1. 中級(難易度 ⭐⭐): Rectangleというクラスを定義し、[幅と高さの2つのプライベート]メンバーを含める。
  1. 上級(難易度 ⭐⭐⭐): Dateというクラスを定義し、[年]、[月]、[日]の3つのプライベートメンバーを含める。

8. 🚀 次は

[クラスとオブジェクトの基礎]を学んだので、[次は] コンストラクタの応用編([第]29[回])――デフォルトコンストラクタ、コピーコンストラクタ、移動セマンティクス(C++11の[新機能])について学びましょう!

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%