c++ - C++ 中带和不带 const 的引用参数 (&)

标签 c++ c++11 reference

所以我昨天在写程序的时候遇到了一个问题,当我使用一个没有const的引用时,以后再调用那个函数就会报错。例如:

bool is_vowel(const string& s) //OK;
bool is_vowel(string& s) //Error!
{
    if (s == "A" || s == "a") return true;
    if (s == "E" || s == "e") return true;
    if (s == "I" || s == "i") return true;
    if (s == "O" || s == "o") return true;
    if (s == "U" || s == "u") return true;
    if (s == "Y" || s == "y") return true;

    return false;
}

并考虑调用此函数的以下内容:(为简单起见,我删除了大量原始代码,因此不要关注此处的逻辑)

int FRI_Syllables(const string& s)
{
    int syllables = 0;

    for (int n = 0; n < s.length(); n++)
        if (is_vowel(s.substr(n, 1)))
            syllables ++;
}

return syllables;

所以当我使用这个函数时,调用 is_vowel 而我不使用 const 的行将返回一个编译时错误,说“没有匹配的调用函数到'is_vowel'”。

我知道为什么这里使用 const 的引用有效;我不明白的是为什么没有的人没有。

另一件让我更困惑的事情是,在 FRI_Syllables 函数中,引用使用 AND 而没有 const。所以考虑调用这个函数的main函数中的一段代码:

int main()
{
    //rest of the code

    int syllables = 0;
    for (int i = 0; i < words.size(); i++)
        syllables += FRI_Syllables(words[i]);

    //rest of the code
}

无论我使用 int FRI_Syllables(const string& s) 还是 int FRI_Syllables(string& s),这都不会返回任何错误。那么为什么会有差异呢?为什么不带 const 的引用有时会起作用而其他的则不起作用?

最佳答案

非 const 左值引用变量仅绑定(bind)到左值,而不绑定(bind)到右值。相比之下,const 左值引用绑定(bind)到左值和右值。

由于 s.substr(n, 1) 的结果是右值(“临时值”),它不能绑定(bind)到非常量左值引用。

这种语言设计选择背后的原因是非常量左值引用的目的是允许您更改被引用的对象,但是当该对象是临时的时,更改会立即丢失,所以这基本上不是您想要的。

关于c++ - C++ 中带和不带 const 的引用参数 (&),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23093983/

相关文章:

c++ - 将 gtest 与 Android NDK 结合使用时出现语法错误

c++ - 观看变量时 Visual Studio 2005 崩溃

c++ - 使用 '&'进行迭代时 'auto'符号有什么作用

c++ - C++ 中的默认函数参数必须保持不变吗?

c++ - 与全局数组相比,为什么在堆中为局部数组分配内存更快?

c++ - 重载前模板实例化错误

c++ - 没有匹配的成员函数来调用 child.value

c++ - 在类外部初始化的 constexpr 静态成员的声明中是否需要 constexpr 说明符?

C++ 对析构函数的 undefined reference

java - 创建变量的别名/引用 (JAVA)