Как я могу сказать объекту, сколько раз он был создан? [Дубликат]

bool GetList (const std::string& src, std::vector<int>& res)
  {
    using boost::lexical_cast;
    using boost::bad_lexical_cast;
    bool success = true;
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> sepa(",");
    tokenizer tokens(src, sepa);
    for (tokenizer::iterator tok_iter = tokens.begin(); 
         tok_iter != tokens.end(); ++tok_iter) {
      try {
        res.push_back(lexical_cast<int>(*tok_iter));
      }
      catch (bad_lexical_cast &) {
        success = false;
      }
    }
    return success;
  }
-1
задан Mugen1994 18 January 2019 в 13:33
поделиться

1 ответ

Вам необходимо создать нестатическое поле, которое вы будете приписывать каждому экземпляру

class K{

   static int instancesCount; 
   // Or "static AtomicInteger instancesCount;" if you do multithreading

   final int nth_instance; // this is your non-static field


   K(){
     instancesCount++;
     this.nth_instance = instancesCount;

     // In case of multithreading, replace both lines by
     // this.nth_instance = instancesCount.incrementAndGet();
   }                 

   public static void main(String[] args){
     K k1 = new K(); //k1.nth_instance == 1;
     K k2 = new K(); //k1.nth_instance == 2;
   }
 }
0
ответ дан Ricola 18 January 2019 в 13:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: