c++字符串字面值和string类型

最近在阅读Accelerated C++这本书的时候遇到一道有意思的题目,然后才有这一篇文章。

1.字符串字面值

字符串字面值(string literal)又称为字符串常量(string constant),是指用双引号包括起来的字符串,

如:

"hello"

在c++中,字符串字面值实际上是一个const char [] 的数组类型。

我们可以用 typeid("hello").name()得到 "hello"字符串字面值的类型

cout << "\"hello\"的类型: " << typeid("hello").name() << endl;
// "hello"的类型: char const [6]

我们可以使用以下几种方式接收一个字符串字面值

	const char * str1 = "aaa";
	const char str2[4] = "aaa";
	const char str3[10] = "aaa";
	cout << str1 << endl;
	cout << str2 << endl;
	cout << str3 << endl;
    //以上输出都是 aaa

    //char * str4 = "aaa";
    //str4写法是错误的,没有加上const 
    
	char* str5 = (char*)"aaa";
	cout << str5 << endl;
    //str5的写法是正确的,这边采用了强制类型转换

    char str6[] = "ssss";
	cout << str6 << endl;
    //str6的写法是正确的

2.Acceletated C++上那道题目(这边做一定改编)

案例一:
 

string str1 = "hello";
string str2 = "world";
string str3 = str1 + str2;   //这个案例显然是可以运行成功的

            这个案例显然可以成功运行

案例二:

string str1 = "hello";
string str2 = str1 + "world";

            这个案例是可以成功运行的,在进行相加时 “world”字符串字面值会被编译器自动转换为 string 对象

案例三:

string str1 = "world";
string str2 = "hello" + str1;

              这个案例不能成功运行,"hello"字符串字面值没有被编译器自动转换,而const char []类型的变量无法相加(没有进行+运算符的重载)

文章到这里就结束了,很多细节方面的这边没有展示,原因1是防止文章篇幅过长,原因2是细节方面的主要是自己的理解,还需要查找资料或者查阅书籍验证。
我的C++版本:C++20
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值