简体   繁体   中英

Can we have a static class in C++?

I was just wondering whether we can have static classes in C++. What I mean is can we declare a class as static in C++ like static class foo ? I know we can have static member variables and static member functions in C++ but I am not sure about static classes.

Edit:

I intended to ask what does it mean for a class to be static.

static is a storage class specifier.

  • Applied to variables, it specifies the object's lifetime and visibility -- in this case, the lifetime is the entire program's execution, and the visibility is restricted to the particular translation unit (usually a given source file).
  • Applied to functions, it similarly specifies the object's visbility -- limited to the particular translation unit in which it is defined.
  • Applied to class members variables and functions, it defines the variable to be a property of the class, and not the object itself.

So that's the semi-pedantic definition. The question is, what semantics exactly would you like to attach to the idea of a "static class"? Nested classes automatically have static-like properties -- they are a property of the class, and not the individual object. If you wanted static-like properties for a class declared in an outer scope (ie not conflicting with the one-definition rule across different translation units), you can use an anonymous namespace .

The static keyword implies that the object that it refers to exists through the life of the entire program. A class definition is just an outline for constructing an object.

With that in mind, perhaps you might be looking to do something like create a namespace or create a singleton object , a class that is designed to only ever have a single instance.

No, but you can basically achieve nearly the same if you create a class with static methods (and data) only. Beware thought, there is no static constructor concept in C++.

If by "static class" you are referring to the ones in C#, then the equivalent in C++ is to just make a single constructor and make it private, and avoid making non-static members.

If by "static class" you are referring to the ones in Java, then all C++ classes are "static", so you can't add "static" because it would be redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM