C++中运算符重载!判断对象中字符串是否为空

#include <iostream>
#include <string.h>
using namespace std;

class String
{
private:
char* str;
public:
String(char* p = "")
{
str = new char[strlen(p)+1];
strcpy(str, p);
}
~String()
{
delete[] str;
}
friend int operator !(String& x);
};
int operator!(String& x)
{
if (strlen(x.str) == 0)
return 1;
else
return 0;
}
int main()
{
String s1("A String!"), s2;
if (!s1)
cout << "s1 is null!" << endl;
else
cout << "s1 is not null!" << endl;
if (!s2)
cout << "s2 is null!" << endl;
else
cout << "s2 is not null!" << endl;
}
我不太明白这里
if (strlen(x.str) == 0)
return 1;
else
return 0;
能帮我解释下为什么 为空返回1 ???? 谢谢

1为true,因为!操作使得 为空是时string为假 !string为真,不为空时string为真 !string 为假
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-06-22
C语言中,非零为真, 1代表True.
第2个回答  2013-06-22
如果为空,返回值为一。即函数的结果为一,主函数根据返回值是否为一判定是否为空。
第3个回答  2013-06-22
不在于数字是一 而在于返回真 零 为 假 ; 非零 为 真; 只是返回一个非零值而已 返回值为重载运算符做判断使用

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网