所以我在写一个程序,其中一个功能就是判断这个字符是否是元音。程序如下:
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 转换为引用参数 string& s 时,我的问题就出现了。更改后,每当我尝试调用此函数时,程序(顺便说一句,我在 Mac 上使用 Xcode)都会告诉我 “没有调用'is_vowel'的匹配函数”
,即使 IS 内部的对象一个字符串对象。那么为什么我不能在这里使用引用参数呢? “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: error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘const char*’ cout << is_vowel("f") << endl;
如果这是您的情况,这是使用 const 引用而不是引用的另一个原因。您也可以使用值语义,但我同意您的引用结论。
关于c++ - C++ 中 bool 函数没有引用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23069732/