I have a salon class with a car field; How to find the sum of all car, if I do not know how many objects will be initially?

class salon { int car; public : //////какие то функции } int main() salon s1; salon s2; salon s3; //// сумма s1.car +s2.car + s3.car .. +sn.car 

Closed due to the fact that the essence of the question is incomprehensible by the participants αλεχολυτ , cheops , aleksandr barakin , Streletz , user207618 27 Sep '16 at 17:59 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • in your case, you will not be able to contact car, because with this declaration it will be considered a private member. - bronstein87
  • one
    It would be interesting to listen to your decision if you initially know the number of objects ... :) - Harry
  • If the number of terms you do not know, how do you get their sum? - Vladimir Gamalyan

2 answers 2

Enter the static variable static unsigned int NCar; into the class static unsigned int NCar; immediately after the class declaration: NCar = 0; and in the constructor or in the function where the number of cars in the cabin is NCar += car : NCar += car .

  • We must not forget to reduce in the destructor, and take care of the copy constructor and the assignment operator. For complete happiness. But the question is, in fact, not clear enough in its current form. - αλεχολυτ

use a dynamic array, or vector, and iterate through the fields somehow

 vector<salon> salons; vector<salon>::iterator itSalon; //заполняешь вектор int cars = 0; for(itSalon = salons.begin(); itSalon != salons.end(); ++itSalon) { cars += itSalon->car; } 
  • one
    When calculating the amount in one form or another, it is recommended to use the std::accumulate algorithm instead of manually creating a loop. - αλεχολυτ