C ++: accessing constant elements via class or instance?

In C ++, is there any reason not to access static member variables through an instance of the class? I know Java frowns at this and wonders if this matters in C ++. Example:

class Foo {
  static const int ZERO = 0;
  static const int ONE = 1;
  ...
};


void bar(const Foo& inst) {
   // is this ok?
   int val1 = inst.ZERO;
   // or should I prefer:
   int val2 = Foo::ZERO
   ...
};

I have a second bonus question. If I declare a static double, I have to define it somewhere, and this definition should repeat the type. Why should the type be repeated? For example:

In a header:
  class Foo {
    static const double d;
  };
In a source file:
  const double Foo::d = 42;

Why do I need to repeat the "const double" part in my cpp file?

+3
source share
6 answers

, ( , ), . , . ( , , , . .)

:

"const double" cpp?

: ++ . , ++ 1x ( ++ 0x) auto, .

, :

vector<string> v;
vector<string>::iterator it = v.begin();

:

vector<string> v;
auto it = v.begin();

, , thos:

const double Foo::d = 42;

.

static Foo::d = 42;

.

. : ++ - : . , , . , . ... ++ 2x:/.

+5

Foo::ZERO inst.ZERO, , . Foo ZERO.

, const .

+6

, , Foo:: Zero, .

, .. Foo:: ZERO Foo:: Zero. - ++ , ++, .

+3

Foo:: ZERO, . , Foo, .

, .

, , , const const. . , , .cpp. (, gcc).

+1

, . . , , .

, , - . . , .

, , . . , .

+1

. ::)

. Foo:: Zero, , . inst.Zero , , inst .

You have to repeat the data type because this is how C ++ works. Similarly, if you wrote the following in the header file.

extern int foo;

You still need to specify

int foo

in the CPP file. As mentioned in pukku, you are declaring a variable of type "const int". Thus, "const int" must be repeated in the definition of the variable.

+1
source

Source: https://habr.com/ru/post/1714555/


All Articles