C++中没有布尔函数的引用参数

No reference parameter for bool function in C++?

本文关键字:引用 参数 函数 布尔 C++      更新时间:2023-10-16

所以我在写一个程序,其中一个功能是确定字符是否是元音。程序如下:

bool is_vowel(string s)
{
    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;
}

所以当我试图把字符串s变成一个引用参数字符串&更改后,每当我试图调用此函数时,程序(我在Mac btw上使用Xcode)都会告诉我"No matching function for call to 'is_vowel'",即使其中的对象是字符串对象。为什么我不能在这里使用引用参数呢?"s"不是指我用来调用这个函数的任何字符串吗?我在大多数函数中都使用了引用参数,在这些函数中我不会更改任何内容,因为我认为引用而不是将值复制到新参数中可能更有效。为什么它在这里不起作用?顺便说一句,"引用而不是将值复制到新参数中更有效"是真的吗?

编辑:根据许多人的请求,我只添加一个调用此函数的其他函数;为了简洁起见,我截取了一大块代码。所以,不要过多地纠缠于这部分的逻辑。

int FRI_Syllables(vector<string>& s)
{
    int syllables = 0;
    for (int i = 0; i < s.size(); i++)
    {
        string word = s[i];
        for (int n = 0; n < word.length(); n++)
        {
            if (is_vowel(word.substr(n, 1)))
                syllables ++; //Rule 1: count each vowel as a syllable
        }
    }
    return syllables;
}

至于对bool函数的更改,除了第一行是之外,其他一切都是一样的

bool is_vowel(string& s)

Xcode给我的错误是"调用'is_vowel'没有匹配的函数"。

首先,当您不像在这种特殊情况下那样更改值时,您希望使用const引用,而不是引用。

第二,字符串对字符来说是一种过度使用。

第三,代码对我来说很好,如下所示:

#include <iostream>
#include <string>
using namespace std;
bool is_vowel(const string &s)
{
    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 main()
{
    string mystring = "b";
    string mystring2 = "A";
    cout << is_vowel(mystring) << endl;
    cout << is_vowel(mystring2) << endl;
    return 0;
}

如果我只传递如下字符串文字,我可以重现您的问题:

main.cpp:24:25:错误:类型为"std::string&"{aka std::basic_string&}"来自类型为"const char*"的右值cout<lt;is_vowel("f")<lt;endl;

如果是这种情况,这是使用const引用而不是引用的另一个原因。您也可以使用值语义,但我同意您的参考结论。