C++字符串定义区别

#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";


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值