static class real life significance

2019-09-21 02:55发布

I read a lot on static keyword, I only found static variable, static function, but there is no discussion of static class, can you please explain me about this.

  • Why we use static class in c++?
  • Why we introduce this type of class?
  • Give the physical significance of static class?
  • Give the real life example of static class?
  • If there is any limitation, then tell me what?

I am waiting for your reply. Thanks in advance.

1条回答
做自己的国王
2楼-- · 2019-09-21 03:34

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;
}
查看更多
登录 后发表回答