RWCString 和 const char * 之间的隐式转换
RWCString str = "Y";
str.append("ES");
if("YES" == str)
cout << "YES == str" << endl;
if(str == "YES")
cout << "str == YES" << endl;
在这两种情况下,隐式转换是如何发生的?哪一种可以安全使用? RWCString 是一个字符串类,它有一个采用 const char* 的构造函数和一个到 const char* 的转换运算符
RWCString str = "Y";
str.append("ES");
if("YES" == str)
cout << "YES == str" << endl;
if(str == "YES")
cout << "str == YES" << endl;
How does the implicit conversion take place in both cases? Which one is safe to use?
RWCString is a string class which has a constructor taking const char* and an conversion operator to const char*
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
const char*
和RWCString
之间的比较,==
极有可能被重载。否则,要么将
str
转换为const char *
,要么调用不明确:如果存在外部或外部调用,则
str == "YES"
是不明确的。成员operator==
比较两个RWCString
。如果存在外部
operator==
比较两个RWCString
,则"YES" == str
是不明确的。(假设
operator==
的参数正常传递——通过副本或const
引用)。It is extremely likely that
==
is overloaded for comparisons betweenconst char*
andRWCString
.Otherwise either
str
is converted toconst char *
or the calls are ambiguous:str == "YES"
is ambiguous if there is an external or memberoperator==
comparing twoRWCString
s."YES" == str
is ambiguous if there is an externaloperator==
comparing twoRWCString
s.(assuming that the arguments to the
operator==
are passed normally -- either through a copy, or aconst
reference).