最近在阅读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 []类型的变量无法相加(没有进行+运算符的重载)