[英]Dynamic variable doesnt work
in this code why does the first("invNummer") is always 0, when I initializate it dynamically? 在此代码中,当我动态初始化它时,为什么first(“ invNummer”)始终为0? 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: 正如@ It's_comming_home向您指出的那样 ,您的问题与动态创建
one
对象无关,而与该对象的删除有关:
delete one;
When you delete the one
object, the pointer is left dangling, ie it is no longer usable. 删除
one
对象时,指针将悬空,即不再可用。 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()
方法后移动其删除即可:
one->info();
two.info();
delete one;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.