同じ名前、および引き数の数と型が同じである、静的メンバー関数と非静的メンバー関数を持つことはできません。
静的データ・メンバーのように、クラス A のオブジェクトを使用しないで、 クラス A の静的メンバー関数 f() にアクセスできます。
静的メンバー関数は、this ポインターを持ちません。 次の例は、このことを示しています。
#include <iostream> using namespace std; struct X { private: int i; static int si; public: void set_i(int arg) { i = arg; } static void set_si(int arg) { si = arg; } void print_i() { cout << "Value of i = " << i << endl; cout << "Again, value of i = " << this->i << endl; } static void print_si() { cout << "Value of si = " << si << endl; // cout << "Again, value of si = " << this->si << endl; } }; int X::si = 77; // Initialize static data member int main() { X xobj; xobj.set_i(11); xobj.print_i(); // static data members and functions belong to the class and // can be accessed without using an object of class X X::print_si(); X::set_si(22); X::print_si(); }
次に、上記の例の出力を示します。
Value of i = 11 Again, value of i = 11 Value of si = 77 Value of si = 22
コンパイラーは、このメンバー関数が静的として宣言されていて、そのため メンバー関数が this ポインターを持っていないので、関数 A::print_si() で、 メンバー・アクセス操作 this->si を認めません。
非静的メンバー関数の this ポインターを使用して、静的メンバー関数を呼び出すことができます。 以下の例では、非静的メンバー関数の printall() が、this ポインターを使用して 静的メンバー関数の f() を呼び出します。
#include <iostream> using namespace std; class C { static void f() { cout << "Here is i: " << i << endl; } static int i; int j; public: C(int firstj): j(firstj) { } void printall(); }; void C::printall() { cout << "Here is j: " << this->j << endl; this->f(); } int C::i = 3; int main() { C obj_C(0); obj_C.printall(); }
次に、上記の例の出力を示します。
Here is j: 0 Here is i: 3
キーワード virtual、const、volatile、 または const volatile を使用した静的メンバー関数の宣言はできません。
静的メンバー関数がアクセスできるのは、その関数が宣言されているクラスの静的メンバー、列挙子、および ネスト型の名前だけです。 静的メンバー関数 f() が、クラス X のメンバーであるとします。 静的メンバー関数 f() は、非静的メンバー X または基底クラス X の 非静的メンバーにアクセスできません。
関連参照