我正在使用 cpp.sh编译并运行这段代码。我希望 number
的值默认初始化为 0
或一些垃圾值。但是,在构造函数中,即使 if
条件为假,number
的值仍被初始化为 10
。有人可以向我解释发生了什么吗?
#include <iostream>
class Number
{
int number;
public:
Number(std::string s)
{
if (s == "foo")
{
number = 10;
}
}
int getNumber()
{
return number;
}
};
int main()
{
Number n("bar");
std::cout << n.getNumber() << std::endl;
}
最佳答案
来自 [dcl.decl] 中的第 9 条
If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced
值 10 的放置就像编译器为消除条件语句所做的优化一样。
关于字符串比较的 C++ 奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48782805/