[英]c++ function pointer to class member compile error for std::string but ok for custom class
[英]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.