Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ クラスの静的メンバー | イントロダクション
C++のクラスとオブジェクト

bookクラスの静的メンバー

メニューを表示するにはスワイプしてください

オブジェクト指向プログラミングにおいて、static キーワードは特別な意味を持ち、属性やメソッドの動作を変更します。各インスタンスごとにデータを複製するのではなく、クラスのすべてのオブジェクト間で特定のデータを共有する必要がある場合があります。ここで 静的データメンバー が活用されます。

静的メンバーの構文

クラス静的メンバーを作成するのは簡単です。宣言の前に static キーワードを付けるだけです。

Example.h

Example.h

copy
12345
class Example { public: static int static_attibute; static void static_method() { std::cout << "Static method!" << std::endl; } };

上記の例では、static_attributestatic_method()class Example静的データメンバーとして宣言されています。通常のデータメンバーとは異なり、静的データメンバーは個々のオブジェクトではなく、クラス自体に関連付けられます。つまり、Example のすべてのインスタンスが同じ静的メンバーを共有します。

静的データメンバーの初期化は重要であり、メンバーが const キーワードも使用していない限り、クラスの外部で行う必要があります。

FirstExample.h

FirstExample.h

SecondExample.h

SecondExample.h

copy
1234567
class Example { public: static int static_attribute; static void static_method() { std::cout << "Static method!" << std::endl; } }; int Example::static_attribute = 0;

静的メンバーの利点

静的データメンバーおよび静的メンバー関数の使用には、いくつかの利点があります。

main.cpp

main.cpp

copy
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 }
question mark

次のうち、静的メンバー変数に関する正しい記述はどれですか?

すべての正しい答えを選択

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  6

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  6
some-alt