#include <iostream>
#include <string>
using namespace std;
int main(){
char p[] = "hello";
string s = "hello";
char *q = "hello";
cout << (p == s);
cout << (p == q);
cout << (s == q) << endl;
cout << (p == "hello");
cout << (s == "hello");
cout << (q == "hello") << endl;
cout << hex << (q - p) << endl;
cout << p << endl << s << endl << q << endl;
cout << hex << (int)p << endl;
cout << hex << (int)q << endl << (int)("hello") << endl;
char *p1 = "hello";
char *p2 = "hello";
cout << (p1 == p2) << endl;
cout << (&p1 != &p2) << endl;
cout << "///" << endl;
char * qq = "iello";
cout << ("hello" > "iello") << endl;
cout << (q > qq) << endl;
cout << hex << int(q) << endl << int(qq) << endl;
return 0;
}
输出结果:
101
011
2ea3c4
hello
hello
hello
12ff24
41a2e8
41a2e8
1
1
//
1
1
41a2e8
41a2cc
结论:
char * q = "hello"; q为常量,存在静态存储区。
sting s = "hello"; string对==做了重载,与一切看上去相等的作比较,结果都为相等。
char p[] = "hello"; p为变量,存在栈区,与常量比较不相等(转解释1)。
p1和p2存的地址是相同的,都是常量"hello"在静态存储区中的地址。
存p1和存p2的地址不同。
解释1:
q和"hello"比较的是地址,地址相同;
p和"hello"比较的是地址,地址不同。
("hello" > "iello")结果为1可以证明:字符串比较结果应该为1,但是此处为比较地址的大小,"hello"地址比"iello"大。
另外:
char *p = "hello" 和 const char *p = "hello" 等价,前者是C历史遗留,应淘汰。
char *p 和char p[]都没有操作符重载,各种符号(==,!=,<,>,<=,>=)比较都是对地址进行比较,相同的常量字符串拥有相同的地址。
string 有操作符重载,各种符号(==,!=,<,>,<=,>=)比较的是地址中的内容。
char p1[] = { '1', '2', '3' }; //不是字符串
char p2[] = { '1', '2', '3', '\0'}; //是字符串
char p3[] = "123";