クラスの静的メンバー
メニューを表示するにはスワイプしてください
オブジェクト指向プログラミングにおいて、static キーワードは特別な意味を持ち、属性やメソッドの動作を変更します。各インスタンスごとにデータを複製するのではなく、クラスのすべてのオブジェクト間で特定のデータを共有する必要がある場合があります。ここで 静的データメンバー が活用されます。
静的メンバーの構文
クラスの静的メンバーを作成するのは簡単です。宣言の前に static キーワードを付けるだけです。
Example.h
12345class Example { public: static int static_attibute; static void static_method() { std::cout << "Static method!" << std::endl; } };
上記の例では、static_attribute と static_method() は class Example の静的データメンバーとして宣言されています。通常のデータメンバーとは異なり、静的データメンバーは個々のオブジェクトではなく、クラス自体に関連付けられます。つまり、Example のすべてのインスタンスが同じ静的メンバーを共有します。
静的データメンバーの初期化は重要であり、メンバーが const キーワードも使用していない限り、クラスの外部で行う必要があります。
FirstExample.h
SecondExample.h
1234567class Example { public: static int static_attribute; static void static_method() { std::cout << "Static method!" << std::endl; } }; int Example::static_attribute = 0;
静的メンバーの利点
静的データメンバーおよび静的メンバー関数の使用には、いくつかの利点があります。
main.cpp
12345678910111213141516171819202122#include <iostream> class Example { public: static int static_attribute; static void static_method() { std::cout << "Static method!" << std::endl; } }; // Initialization of the static member variable int Example::static_attribute = 0; int main() { Example obj1, obj2; obj1.static_attribute = 100; // Modifying static_attribute through obj1 std::cout << obj1.static_attribute << std::endl; std::cout << obj2.static_attribute << std::endl; Example::static_attribute = 25; // Modifying static_attribute through class Example::static_method(); // Calling the static method through class }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 6
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 6