There are no static classes in C++. static
refers to a storage class, i.e. it applies to objects or functions, not to data types.
In Java, static class
, when applied to classes that are nested in other classes, means that the nested class can be instantiated independently of any instance of the enclosing class. In C++ that is always the case. Nested classes in C++ are always independent data types.
Here is what I mean: First let's take a look at this Java code:
public class A {
public class B {
}
public static void main(String[] args)
{
A.B b1 = new A.B(); // <-- This is ill-formed, because A.B is not
// an independent data type
A a = new A();
A.B b2 = a.new B(); // <-- This is correct. Use an instance of A to
// create an object of type A.B.
}
}
It defines a class A
, and a nested class (i.e. a member class, or sub-class) A.B
. The second line of the main program shows how you cannot instantiate a object of type A.B
. You cannot do this because B
is a member class of A
and therefore requires an existing object of type A
to be instantiated. The third line of the main program shows how this is done.
In order to be able to instantiate an object of type A.B
directly (independently of any instance of type A
) you must make B
a static member class of A
:
public class A {
public static class B { // <---- I inserted 'static'
}
public static void main(String[] args)
{
A.B b1 = new A.B(); // <-- This is now well-formed
A a = new A();
A.B b2 = a.new B(); // <-- This is now ill-formed.
}
}
On the other hand, in C++ this is not required, because in C++ a member class is always an independent data type (in the sense that no instance of the enclosing class is required to be able to create instances of the nested class):
class A
{
public:
class B
{
};
};
int main()
{
A::B b; // <--- Perfectly well-formed instantiation of A::B
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…