[英]error: cannot resolve overloaded function based on conversion to type ‘int’
I wrote the following code:我写了以下代码:
#include<bits/stdc++.h>
using namespace std;
int lengthOfLastWord(string A) {
int m= A.size();
int i=0;
while(i<m)
{
if(A[i]==' ')
{
int count=0;
i++;
while(A[i]!=' ')
{
count++;
i++;
}
}
else
i++;
}
return count;
}
int main()
{
string A;
getline(cin,A);
cout<<lengthOfLastWord(A);
}
But it is showing the following error但它显示以下错误
error: cannot resolve overloaded function ‘count’ based on conversion to type ‘int’
I am unable to understand why is it showing this error and what should I do to fix it.我无法理解为什么它会显示此错误以及我应该怎么做才能修复它。 Please help me.请帮我。 Thankyou谢谢
Inside the if
scope, your count
variable is colliding with (technically "shadowing") std::count
.在if
scope 内部,您的count
变量与(技术上“阴影”) std::count
发生冲突。 However, your local count
does not exist in the scope of your return
statement, so the compiler is trying to use the only count
that it knows about at that point, which is std::count
.但是,您的本地count
不存在于您的return
语句的 scope 中,因此编译器正在尝试使用它当时知道的唯一count
,即std::count
。
This is a great example of why using namespace std
and #include<bits/stdc++.h>
are both bad ideas.这是一个很好的例子,说明为什么using namespace std
和#include<bits/stdc++.h>
都是坏主意。 If proper includes and namespaces were used, this code would have given you a much clearer compile error:如果使用了正确的包含和命名空间,这段代码会给你一个更清晰的编译错误:
error: 'count' was not declared in this scope
The most direct reason is because your count
variable is defined in the if
scope, and not available in the scope of return
statement.最直接的原因是因为你的count
变量是在if
scope中定义的,而在return
语句的scope中没有。
However, the error you are seeing is confusing, since you have using namespace std
in your code, and it makes completely unrelated (for your purposes) function std::count
visible everywhere in your program, including your return
statement.但是,您看到的错误令人困惑,因为您在代码中using namespace std
,并且它完全不相关(出于您的目的) function std::count
在您的程序中随处可见,包括您的return
语句。 From the compiler perspective, you are trying to return a pointer to std::count
, but since this function is overloaded template, compiler doesn't know which one you are trying to return - thus the phrasing of the errror.从编译器的角度来看,您正在尝试返回指向std::count
的指针,但由于此 function 是重载模板,因此编译器不知道您要返回哪个 - 因此是错误的措辞。
If you remove the using namespace std
from your code, which you should have never had in the first place, your code will still fail to compile, but error message would be way more easier to understand.如果您从代码中删除using namespace std
,这是您一开始就不应该拥有的,您的代码仍然无法编译,但错误消息会更容易理解。
One solution is to rename your count variable to something else like total
.一种解决方案是将您的 count 变量重命名为其他名称,例如total
。
The compiler is considering std::count
function instead of the count variable which is int
.编译器正在考虑std::count
function 而不是 count 变量int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.