简体   繁体   中英

Class scope constants: const vs static const

For constants of a class, should I use class scope static const, or file scope const?

For example:

// .h
class C {
  private:
    static const int some_constant_c;
}

// .cc
const C::some_constant_c = 10;

vs.

// .h
class C {
}

// .cc
const some_constant_c = 10;

To me, the former one have better semantic meaning that the constant is of a certain class, but the latter one have the advantage not exposing constants to header file.

==============

One follow up question on this:

What if I want my constants be accessed by subclasses. Make sense to put static const in protected ? Example follows:

// .h
class C {
  protected:
    static const int some_constant_c;
}

It's a matter of personal preference, of course. Trying not to expose class internals in the header file is a ship that has most definitely sailed in C++... between member variables and private member functions, it's just not practical to keep implementation details out of the header (unless you're using the pImpl idiom).

If all you want is to hide the value of the constant, note that you can put the initializer in the source file instead.

If you do implement the constants as globals in the source file, use an anonymous namespace to keep them from causing linker collisions.

I'd prefer 2nd variant, provided the const in the 1st case is private.

Why should one pollute the class declaration with redundant information? Consider, you are implementing a protocol parser, with many many constants. How will the class declaration look like?

Another issue is, why should you type the name of the const twice? I try to keep definition and initialization as close as possible.

Just an opinion.

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