刚学C++,看书上说几种常量,数值常量我能理解,PI是个好例子。但是字符常量又要作何解?转义字符这个倒还好理解,有个实际用处单独定义出来。但是还有普通的字符常量,这个我就非常理解不能了,请问大家能不能给个例子证明这个有什么用?而且只能单引号什么的其实也挺纠结的。
另外,C++是不是强语言,每个变量都必须定义类型什么的?没办法,从PHP转过去的,挺纠结这些基本问题的╮(╯▽╰)╭...
再来就是定义字符串常量查到好几种方法:
#include<string> string url = "segmentfault.com";
const char url[] = "segmentfault.com";
const char *url = "segmentfault.com";
const char* url = "segmentfault.com";
请问哪个好点?另外最后两个的*号做何解...新手问题还望大家要淡定,别凌乱就好。。。。
大家讲道理2017-04-17 11:04:23
Let’s first talk about the differences between these examples:
1.
#include<string> string url = “segmentfault.com”;
url is a string object. In order to manipulate strings more easily, cpp defines a string class for us (string is not a keyword of cpp). You can use it to define a string object, and then get the information of the string by calling its method. For example, get its length:
url.length()
Or manipulate it, such as splicing:
string scheme = “http://” cout << scheme+url << endl; //输出http://segmentfault
2,
The following three writing methods can all be regarded as one:
const char* url = “segmentfault”;
Because const char url[] (character array), the array name url will be implicitly converted to a pointer char* during compilation, pointing to the first character 's' of the string. As for the position of the * sign, some people like to put it close to the type, and some people like to put it close to the variable name. Here is a topic to discuss this issue
http://topic.csdn.net/u/20101117/10/f...
And because it is a constant string, you cannot modify it
url[0]='x';//错误,不可以进行修改,就算没有用const来修饰,也不可以
But it works in string
string url = “segmentfault.com”; url[0] = 'x';//OK
This is because string takes on the task of managing memory for us. If you want to splice it, you need to write a function yourself, or call the strcat or strncat function in the cstring library.
In c/cpp, * has two functions. One is used to define pointer types. char* is a character pointer. The other is to get the value, get the value pointed by the pointer, think of the above
const char *url = “segmentfault”;
url points to the first character of the string, so when you evaluate the pointer url, you get the character 's'
cout << *url << endl;//输出's'
So, in general, string is more convenient to use, while constant string is a bit troublesome to manipulate. It can also be said to be flexible. When to use which one, you need to measure it yourself. As for performance, I don’t think I have the ability to analyze it yet!
伊谢尔伦2017-04-17 11:04:23
Additional to @Henry’s answer
String arrays and pointers are very similar. Arrays can degenerate into pointers when used, but they are conceptually different.
The key point is that the pointer stores an address.
For example:
const char str[] = "segmentfault.com"; const char *str_ptr = "segmentfault.com"; // sizeof(str) == 17 // sizeof(str_ptr), 平台相关, x86的目标文件一般为4(32位), x86_64的目标文件一般为 // 8(4位)
EDIT:
Using this, the length of the string can be determined at compile time.
After understanding that pointers are addresses, the following mistakes will not be made:
define.c
// 定义该字符串常量 const char str[] = "segmentfault.com";
main.c:
// 错误的声明 extern const char *str; // 正确的声明 //extern const char str[]; int main() { // 产生段错误 // 原因: str本来是数组,但是声明为了指针 // 假设目标文件是32位 x86 小端格式 // 则实际访问的错误地址是 0x6d676573 (刚好就是segm这4个字符的ASCII码) printf("%s\n", str); return 0; }
高洛峰2017-04-17 11:04:23
Due to historical reasons, c is compatible with c strings. C-style strings are represented by char[]
or const char *
. String literals are also deduced by the compiler as const char *
.
In the windows environment, the string is compiled and stored in the .rsrc
section (the section can be renamed at will, and different compiler implementations may be different. You can open the peid to check). This section is read-only. If you force write to it, the program will crash, so I will give you const char *
just to be on the safe side.
But modern C programming does not advocate the use of c-style strings (just like obj-c does not advocate the use of c-style strings, but NSString
), so you just need to remember the above point and use std::string
That's it. If you encounter a C-style string, if you want to use it, you should immediately use the constructor of string
to convert it to string
.
Remember, what you write is c , not c!
There are two forms of constructor calls, one is the function form, such as string url("segmentfault.com")
. However, in particular, if the constructor has only one parameter, it can be written in assignment form, that is:
#include<string>
string url = "segmentfault.com";
As long as this is the initialization of the object and a corresponding constructor exists, it will be compiled into a call to the constructor. Instead of creating string
first and then calling operator =
. The actual function of the above sentence is to use const char *
to construct string
.
or if you want the compiler to infer the string
type, add an s after it.
auto url = "segmentfault.com"s;
If you use char []
to save a string, it will be stored on the stack.
is because the name of a native array can be deduced by the compiler as a lower-level pointer pointing to the starting position of the array. For example, char[]
will be treated as char *
when used.
char[]
is different from other arrays in that it can be initialized with string literals.
If you write:
char str[] = "segmentfault.com";
is equivalent to
char str[] = {'s','e','g','m','e','n','t','f','a','u','l','t','.','c','o','m','rrreee'};