C++字串定義區別
阿新 • • 發佈:2019-01-07
#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";