C++中没有静态类.static指的是存储类,即它适用于对象或函数,而不适用于数据类型.
在Java中static class,当应用于嵌套在其他类中的类时,意味着嵌套类可以独立于封闭类的任何实例进行实例化.在C++中总是如此.C++中的嵌套类始终是独立的数据类型.
这就是我的意思:首先让我们来看看这个Java代码:
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.
}
}
Run Code Online (Sandbox Code Playgroud)
它定义了一个类A和一个嵌套类(即成员类或子类)A.B.主程序的第二行显示了如何不实例化类型的对象A.B.您不能这样做,因为它B是一个成员类,A因此需要实例化现有的类型对象A.主程序的第三行显示了如何完成.
为了能够实例类型的对象A.B 直接(独立类型的任何实例A),你必须做出B一个静态成员类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.
}
}
Run Code Online (Sandbox Code Playgroud)
另一方面,在C++中,这不是必需的,因为在C++中,成员类始终是独立的数据类型(在某种意义上,不需要封闭类的实例来创建嵌套类的实例):
class A
{
public:
class B
{
};
};
int main()
{
A::B b; // <--- Perfectly well-formed instantiation of A::B
return 0;
}
Run Code Online (Sandbox Code Playgroud)