动态变量不起作用

时间:2018-07-19 21:35:12

标签: c++ class c++11 dynamic constructor

在此代码中,当我动态初始化它时,为什么first(“ invNummer”)始终为0?当我将其作为静态对象(两个)使用时。

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;
}

输出看起来像这样:

0 Windows 1
9 Linux 0

1 个答案:

答案 0 :(得分:4)

对于您@It's_comming_home pointed out,您的问题与动态创建one对象无关,而与该对象的删除有关:

delete one;

当删除one对象时,指针将悬空,即不再可用。如果您以后尝试取消引用,则:

one->info();

您将得到未定义的行为,如您的输出所示。

要解决此问题,只需在调用one方法后移动info()对象的删除即可:

one->info();
two.info();

delete one;