+ 2
Why can't I print "count"?
I'm able to do it from the constructor, but not a member function. Why? How can I make it work? https://code.sololearn.com/cVzodsR6ZNTt/?ref=app
4 Antworten
+ 3
Because count is declared inside the constructor, therefore it is only accessible inside the constructor.
If you want it to belong to the whole class you should declare it just like all other class variables, but with static added to it.
Initialize it outside the class but not inside the constructor.
e.g.
class T
{
public:
static int foo;
};
int T::foo = 0;
+ 3
I agree with Dennis.
There is also one simple solution to get output you want. (it works but you should listen to Dennis, you should create id variable.)
This is part of your code (lines 65-67):
Person Joshya("Joshya","Cooper", 20, HisBd);
Daniel.printInfo();
Joshya.printInfo();
just cut Daniel.printInfo(); and paste it above Person Joshya("Joshya","Cooper", 20, HisBd);
... and it will work, because you first call constructor and in your constructor count++ is now = 1 then you print info of your first object. After that you create a new object by calling constructor and now count is = 2, then you print info of your second object.
I am coming from Java world, but the concept is similar.
+ 2
I can only get it to print the final count of all objects of the class. I need it to print the number of each person object
let's say I make 2 person objects
Person a(params)
Person b(params)
now if I print the data, I should get something like
"Person #1"
-param data-
"Person #2"
-param data-
(param data being names and age and other data)
+ 2
Yea, you need another variable inside the class called something like id, and assign that id with the value of that static variable inside the constructor before you increment that counter.
You print the id, not the counter.