There is a class.

class some{ public: static int Instances; static int TotalSumm; public: some() { // Конструктор Instances = 0; } } 

This code is not collected. Mistake:

LNK2001 "Unresolved External Character".

What could be the problem?

  • The problem you have in the design of the application. Static fields in classes are a rarely difficult to handle abomination. - gbg

2 answers 2

You declared a static field. But not defined .

Add

 int some::Instances; int some::TotalSumm; 

out of class

After that, do you really need to reset the class member when creating each instance ?

Update . In order not to violate the rule of one definition, these definitions should be located in a single .cpp file, in a single copy. When placed in the header file, they will be defined in each .cpp file of the project ...

  • No, do not reset the member of the class. This is just an example, the real problem is slightly different. I did not want the code to be found through search engines. But your answer still helped me a lot. Is it possible to initialize the field from the class somehow? For example, are mechanisms similar to a static constructor from C #? - user211023
  • If you need initialization - just initialize when defining. Type int some::Instances{5}; or int some::Instances = func(); or, if it is something more serious and has its own constructor - as when defining an object of the corresponding class. For example, suppose there is a class test with a constructor from two int , and in the class static test T; - then define as test some::T{12,18}; or something like that ... - Harry
  • Add that it needs to be done in the cpp file, otherwise odr-violation will come very quickly. - ixSci
  • @ixSci This will be the second question :) Maybe a person has everything in one file? :) - Harry
  • Now in one, tomorrow in two. Don't you think it's worth mentioning? After all, it will help a person in the future. In my opinion, this should be part of the answer to such a trivial question. - ixSci

because you need to initialize outside the class

 class some{ public: static int Instances; static int TotalSumm; public: some() { Instances = 0; } }; int some::Instances = 0; int main(int argc, char *argv[]) { some::Instances = 5; return 0; } 
  • It is not necessary to initialize, it is not a constant field. But to determine - yes, definitely ... - Harry
  • Is it possible to initialize the field from the class somehow? For example, are mechanisms similar to a static constructor from C #? - user211023
  • @ user211023, there is no analogue of a static constructor in C ++, but this behavior can be achieved. See this answer here - ixSci