字符串比较的 C++ 奇怪行为

标签 c++ string

我正在使用 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/

相关文章:

java - Java 中由 new String() 和 new String (""进行的字符串初始化有什么区别?

java - 使用正则表达式为 ArrayList 中的变量赋值

c# - 如何从字符串中获取数字

c++ - 问:如何为所有小部件和小部件类型实现通用的基类信号/插槽功能(通过虚拟基类插槽)?

c++ - 基础类(class)设计的好网站?

c++ - 在eventFilter触发之前发出对象的事件

c - 字符串中相等标记之间的符号

c - 在 C 中按字母顺序对字符串和结构进行排序

c++ - 从 int 映射到类型说明符

c++ - 无法包含 ifstream "fatal error: ' ifstream' 找不到文件”