gpt4 book ai didi

c++ - C++编译器默认什么时候初始化指针?

转载 作者:行者123 更新时间:2023-11-30 04:05:56 24 4
gpt4 key购买 nike

请参阅下面的代码:

class A
{
public:

A()
{
i = 0;

if(pt != NULL)
{
std::cout << "why" << std::endl;
}
}

A(bool flag)
{
i = 0;
pt = new B(3.14);
}

private:

class B
{

public:
B(double in) : j(in) {}

private:
double j;
};

private:

int i;
B *pt;
};

int main(int argc, char *argv[])
{
A obj; // place1

int *p;

if(p != NULL)
{
std::cout << "test2" << std::endl;
}

return 0;
}

在这段代码中,我想知道 pt 是否会被初始化 @place1

另一个问题是,如果我删除obj的定义,test2会打印,如果没有,那是为什么?

最佳答案

p 的值未定义。它可能是 0 或 1 或 2 或......因此,如果今天是您的幸运日,您可能会得到打印品,否则不会。

道德:不要依赖你得到的,自己初始化变量。

关于c++ - C++编译器默认什么时候初始化指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23076108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com