C ++中有和没有const的参考参数(&)

时间:2014-04-15 20:33:56

标签: 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的行将返回编译时错误,说明&#34;没有匹配函数用于调用&#39; is_vowel&#39;&#34 ;.

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

另一件令我更困惑的事情是,在FRI_Syllables函数中,引用与没有const的AND一起使用。因此,考虑调用此函数的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的引用有时会起作用,而其他引用则不会?

1 个答案:

答案 0 :(得分:3)

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

由于s.substr(n, 1)的结果是右值(“临时值”),因此无法绑定到非常量左值引用。

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