繁体   English   中英

C ++查找函数使用std :: string编译时出错

[英]C++ Find Function Compile Error With std::string

我一直在阅读Stroustrup的“ C ++编程语言”以学习如何用C ++进行编程,但是课本中的以下示例代码似乎无法正确编译。

#include <iostream>
#include <iterator>

int main()
{
 std::string s = "Hello!";
 char c = 'l';
 std::cout << "The number of " << c << "\'s in the string " << s << " is " << count(s,c);
}

int count(const std::string& s, char c)
{
    std::string::const_iterator i = std::string::find(s.begin(), s.end(), c);
    int n = 0;
    while(i != s.end())
    {
        ++n;
        i = std::find(i+1, s.end(), c);
    }

    return n;
}

这些是编译错误:

main.cpp:8:92: error: ‘count’ was not declared in this scope
      std::cout << "The number of " << c << "\'s in the string " << s << " is " << count(s,c);
                                                                                            ^
main.cpp: In function ‘int count(const string&, char)’:
main.cpp:13:80: error: no matching function for call to ‘std::basic_string<char>::find(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, char&)’
         std::string::const_iterator i = std::string::find(s.begin(), s.end(), c);

我的代码有什么问题?

第一个错误告诉你,当编译器到达main ,它看不到任何符号count声明。 这是C和C ++的怪异之一。 要解决此问题,请向上移动count的定义,或仅在main之前声明其原型。

发生第二个错误是因为调用了错误的函数。 从传入的参数来看,我猜你的意思是std::find而不是std::string::find 要获取std::find ,还必须包含标题<algorithm>

count方法是在main之后定义的,因此在main不可见。 您必须在main之前定义它,或者可以转发声明 count

int count(const std::string& s, char c) ;//forward declaration

int main()
{

  //code
}

int count(const std::string& s, char c)
{
 //code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM