すでに述べたように、これにより 2 つの個別の変数が作成されます。
A::x;
// and
B::x;
実際、B のメソッドで「x」だけを使用しようとすると、より正確になるまで、より近いスコープ定義のみが使用されます。
#include <iostream>
class A
{
protected:
static int x;
public:
A() { x = 7; }
};
int A::x = 22;
class B:A
{
static const int x = 42;
public:
int a_x() const { return A::x; }
int b_x() const { return B::x; }
int my_x() const { return x; } // here we get the more local variable, that is B::x.
};
int main()
{
B b;
std::cout << "A::x = " << b.a_x() << std::endl;
std::cout << "B::x = " << b.b_x() << std::endl;
std::cout << "b's x = " << b.my_x() << std::endl;
std::cin.ignore();
return 0;
}
出力:
A::x = 7
B::x = 42
b's x = 42
アクセシビリティによってアクセシビリティが制限される可能性があると誰かが言いました。基本変数をプライベートにしても、子クラスからアクセスできるようにはなりません。ただし、変数を保護またはパブリックにする必要がある場合は、明示的なアクセス メソッドを使用するか、先ほど説明したローカル スコープ ルールに依存します。