Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
您只将
a
转换为int
,您就不会使用法律转换器(从<代码> std :: string 无法正常工作,如果您的编译器不警告您,我会感到惊讶),然后将分配给结果(> =
),而不是比较 (==
)(也希望编译器警告您)。后来检查了这些警告:当发生时,它看起来像
gcc
在串联中接受两个构造是完全不同的构造(IT解释if(int(a)) = 1)
as 声明阴影int
变量名为a
,初始化为1
,该>到期之后/链条,它仅在使用
-wall
进行编译时才警告,即使到那时,它也只会抱怨,因为它认为它应该是,如果(int a = 1)
将其制作名称无外括号的阴影变量,ugh。光明的一面是,将分配固定在比较中会揭示另一个问题。这是始终在警告中始终编译的一个很好的理由(-wextra
有时过于健谈,但是-wall
几乎总是指出真正的问题),可悲的是,这是一个相当间接的在这种情况下警告。先前转换一次带有有效的
string
to <<代码> int 转换器如std :: stoi
,然后测试转换的int
值int
s,而不是std :: String
反对int
,例如:或对于更简洁的代码(也没有额外的命名变量):
You only converted to
a
to anint
once, you didn't do it with a legal converter ("constructing" anint
from astd::string
doesn't work like that, and I'd be surprised if your compiler didn't warn you), and you assigned to the result (=
) rather than comparing (==
) (also something I'd expect a compiler to warn you about).Later checked about those warnings: As it happens, it looks like
gcc
accepts both constructs in tandem as a completely different construct (it interpretsif (int(a) = 1)
as declaring a shadowingint
variable nameda
, initialized to1
, that expires after theif
/else if
chain; that's fun). It only warns at all if you compile with-Wall
, and even then, it only complains because it thinks it should beif (int a = 1)
to make the name shadowing variable without extraneous parentheses, ugh. Bright side is that fixing the assignment to a comparison would then reveal the other problem. That's a good reason to always compile with warnings turned up (-Wextra
is sometimes overly chatty, but-Wall
is almost always pointing out real problems), sadly it's a rather indirect warning in this case.Convert it once up front with a valid
string
toint
converter likestd::stoi
, and then test the convertedint
value against otherint
s, notstd::string
againstint
, e.g.:Or for slightly more succinct code (and no extra named variables):