Is redeclare a constant static variable outside the class or not

In C ++ Primer 4th 12.6.2, it is recommended to repeat the static variable const outside the class.

However, the code below is in gcc 4.6.3.

#include <iostream>
using namespace std;

class X {
    public:
    const static int a = 1;
};

// const int X::a;

int main() {
    X x;
    cout << x.a << endl;
    return 0;
}

Should we reuse it?

PS:

As recommended by Potatoswatter, I added a function to use a constant static member as a reference:

const int X::a;

void test(const int& a) {
    cout << a << endl;
}

int main() {
    X x;
    test(X::a);
    return 0;
}

If we did not include const int X::aoutside the class X, it generated an error as shown below

undefined reference to 'X::a'

It is good practice to define a definition outside the class, whether it is constant or not.

+4
source share
3 answers

const static , :

  • (, , ).

static constexpr ( , constexpr), .

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

, , , . .

: [class.static.data] §9.4.2/3.

+2

, , , :

const static int a = 1;

, static ( const static), . , . :

class X
{
public:
      static int i; // declaration
};
int X::i = 0; // definition outside class declaration
+3

http://en.cppreference.com/w/cpp/language/static:

If a static data member of an integral or enumeration type is declared as const (and not volatile), it can be initialized with a parenthesis initializer or equal, which is a constant expression, right inside the class definition. In this case, a definition is not required:

The compiler behaves as expected. It is difficult to judge the “C ++ Primer” recommendation without an adequate context.

+2
source

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


All Articles