in this code why does the first("invNummer") is always 0, when I initializate it dynamically? When I do it as a static(two) it works.
class Computer {
private:
int invNummer;
char* osName;
int state; // 0 – aus, 1 - an
public:
Computer(int INV, char* OS, int st);
void info() {
cout << invNummer << " " << osName << " " << state << endl;
}
};
Computer::Computer(int INV, char* OS, int st)
: invNummer(INV)
, osName(OS)
, state(st)
{};
int main()
{
Computer* one;
one = new Computer(10, (char*)"Windows", 1);
delete one;
Computer two(9, (char*)"Linux", 0);
one->info();
two.info();
return 0;
}
Output looks like this:
0 Windows 1
9 Linux 0
As @It's_comming_home pointed out to you, your issue is not related to creating the one
object dynamically, but to the deletion of that object:
delete one;
When you delete the one
object, the pointer is left dangling, ie it is no longer usable. If you try to dereference it afterwards:
one->info();
You will get undefined behavior , like your output shows.
To fix this, just move the deletion of the one
object after you invoke its info()
method:
one->info();
two.info();
delete one;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.