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.
, ++. , , , undefined. ++. , , , - - ++ , ?
( ) . get() - , .
static , .
[edit:] , int test::s=5; .
int test::s=5;
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... , , .
, ?
(ODR), - . Undefined. , , , , , , ., / ODR.
s , 7.
, , , . Undefined . , , , .test::s , - - t. ( inline, , , test, test::s t .)
test::s
t
inline
test
, ++. , .
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 ...
Source: https://habr.com/ru/post/1749908/More articles:Что произойдет, если пользователь перескакивает более 10 версий перед обновлением, и каждая версия имеет новую модель данных? - iphoneSelect a link from a table with a single selector - javascriptDoesn’t use easy migration, and dozens of updates will kill performance? - iphoneСлушатель событий в PHP - phpHow to reset IIS (or otherwise clear the cache) when restarting a web application? - cachingGCC: Compile assembly with updated code matching? - c ++They say that Mercurial "hg clone" is very cheap ... but is it 400 MB on my hard drive? (on Mac OS X Snow Leopard) - mercurialhow to zoom with zest? - eclipseLiferay - no-fill authentication liferay db - liferayMatching Blob ID across multiple frames in C ++ (image analysis) - c ++All Articles