Outputting each instance value.

Hello I have a problem outputting each
value for the getIndvCost() function and I wanted to
see if anyone knew how to output them using pointers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//John 3:16
#include <iostream>
#include <iomanip>
#include <random>
#include "Stat.h"

using namespace std;

int main()
{
   Statistics *people = nullptr;
   people = new Statistics[100];
   srand (time(NULL));

   for (Statistics *ptr = people; ptr < people + 100; ++ptr)
   {
      (*ptr).addPrice(rand() % 1000000 + 100000);
   }

   cout << fixed << setprecision(2) << endl;
   cout << "Statistics\n{\n";
   for (Statistics *ptr = people; ptr < people + 100; ++ptr)
   {
      cout << setw(2) << "[" << setw(2) << ptr - people << "] = $";
      ptr->getIndvCost();
      cout << endl;
   }
   cout << "}" << endl;

   cout << fixed << setprecision(2) << endl;
   cout << "Total price = $" << (*people).getTotalCost() << endl;
   cout << "Total people = " << (*people).getCount() << endl;
}

Statistics.h
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Duetoronomy 4
#ifndef STAT_H
#define STAT_H

class Statistics
{
   private:
      static double totalCost;
      static double peopleCount;
      int individualCost;
   public:
      Statistics()
      { peopleCount++; }
      
      void addPrice(double p)
      { individualCost += p;
        totalCost += p; }
      
      double getIndvCost()
      { return individualCost; }

      double getTotalCost()
      { return totalCost; }
      int getCount()
      { return peopleCount; }
};

double Statistics::totalCost = 0;
double Statistics::peopleCount = 0;

#endif
Last edited on
We can't tell what your program does without the definition of Statistics.
Fixed.
"that whoever believes in C++ shall not stagnate but will always be learning"

The ptr->getIndvCost(); is like line 2 below:
1
2
3
int main() {
  42;
}

No side-effects (and no output). On the other hand, cout << ptr->getIndvCost(); ...
 
(*ptr).addPrice(rand() % 1000000 + 100000);


Alternative:

 
ptr->addPrice(rand() % 1000000 + 100000);

Last edited on
There is more than two valid syntaxes, are there?
1
2
3
4
5
6
(*ptr).addPrice(42);
ptr->addPrice(42);
ptr[0].addPrice(42);
(*ptr+0).addPrice(42);
(*0+ptr).addPrice(42);
0[ptr].addPrice(42);


If member function is declared static, then there is call without object too:
Statistics::getTotalCost()
Topic archived. No new replies allowed.