Static Initialization Confusion

In some concepts in C ++, I am very confused. For example: I have two files

//file1.cpp
class test
{
    static int s;
    public:
    test(){s++;}
};

static test t;
int test::s=5;

//file2.cpp
#include<iostream>
using namespace std;
class test
{
    static int s;
    public:
    test(){s++;}
    static int get()
    {
    return s;
    }
};

static test t;

int main()
{
    cout<<test::get()<<endl;
}

Now my question is:
1. How do two files connect successfully, even if they have different class definitions?
2. Are the static members s of the two classes connected, because I get the output as 7.

Please explain this concept of statics.

+3
source share
5 answers

, ++. , , , undefined. ++. , , , - - ++ , ?

+3

( ) . get() - , .

static , .

[edit:] , int test::s=5; .

+1

Static - ++, .

File1.cpp "static int s" , s , .

" t", , : . , , . ++ :

namespace
{
  test t;
}

, t File1.cpp t File2.cpp .

File2.cpp get: - , , .

static, , . , :

int add()
{
  static value = 0;
  value++;
  return value;
}

add() 1, 2, 3... , , .

+1
  • , ?

(ODR), - . Undefined. , , , , , , .
, / ODR.

  1. s , 7.

, , , . Undefined . , , , .
test::s , - - t. ( inline, , , test, test::s t .)

0

, ++. , .

In the past, I used a rather cumbersome rule: each library and file must have a private namespace in order to avoid such link conflicts. Or put utility classes directly in the definition of the main class. In any case: not to pollute the global namespace and, most importantly, to ensure the uniqueness of names throughout the project. (Having written that now I notice that I used quite a lot of literal concepts from Java.)

My search for the C static equivalent in C ++ was fruitless ...

0
source

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


All Articles