C++中没有布尔函数的引用参数
No reference parameter for bool function in C++?
所以我在写一个程序,其中一个功能是确定字符是否是元音。程序如下:
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引用而不是引用的另一个原因。您也可以使用值语义,但我同意您的参考结论。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 具有常量引用参数的函数模板专用化
- C++:常量引用参数
- 字符串引用参数的效率C++
- 通过非常量引用参数修改常量引用参数
- 如何将指针变量作为引用参数传递?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 移动类的成员作为常量引用参数传递
- C++带有适用于左值和右值的引用参数的函数
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 委托构造函数和引用参数
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 如何强制函数仅接受左值引用参数
- 模板引用参数推断失败C++
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 将unique_ptr作为引用参数或常量传递unique_ptr引用