It doesn't work because every
personne will have their own copy of
const personne *P;
You could make it "work" by marking
P as
static (as you did for the
num_pers counter) but that's a bad idea -- it's a bad idea because all
personne objects will be able to access it, so then how do you decide which one
delete[]'s it?
My advice, keep
personne simple and unaware of how they're stored.
In other words: keep
personne *P;
external to the
personne class.
Also you are overusing pointers.
15 16
|
char* nom;
char* prenom;
|
This is bad. You must understand that pointers hold a memory address, not a copy of the information itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
char * bad_bad()
{
char s[] = "Will this work?";
return s;
} // <--- s array goes out of scope here
// the pointer returned by bad_bad() is always invalid!
int main()
{
std::cout << bad_bad() << std::endl;
}
|
So if you get the person name from a function, the
personne::nom will become invalid.
This all only works now because you use string literals such as
"Loulou"
. String literals are built-in into the program and are always valid while the program runs.
What's more, all copies will be shallow, and not deep.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
struct Person
{
char *name;
};
int main()
{
char tmp[] = "Kyle";
Person a, b;
a.name = tmp;
b = a;
tmp[0] = 'L'; // how much does this affect?
std::cout << a.name << ' ' << b.name;
}
|
Lyle Lyle |
So instead of
char pointers, you should go the C++ style and use
std::string.
1 2 3 4 5 6
|
#include <string>
// ...
std::string nom;
std::string prenom;
|