这里有两行代码
const char * s1 = "test";
char s2 [] = "test";
两行代码具有相同的行为,所以我看不出我应该更喜欢 s1
而不是 s2
还是相反。除了s1和s2,还有使用std::string
的方式。我认为使用 std::string 的方式是最优雅的。在查看其他代码时,我经常看到人们使用 const char *
或 char s []
。因此,我现在的问题是,什么时候应该使用 const char * s1
或 char s []
或 std::string
?有什么区别,在什么情况下我应该使用哪种方法?
最佳答案
POINTERS
--------
char const* s1 = "test"; // pointer to string literal - do not modify!
char* s1 = "test"; // pointer to string literal - do not modify!
// (conversion to non-const deprecated in C++03 and
// disallowed in C++11)
ARRAYS
------
char s1[5] = "test"; // mutable character array copied from string literal
// - do what you like with it!
char s1[] = "test"; // as above, but with size deduced from initialisation
CLASS-TYPE OBJECTS
------------------
std::string s1 = "test"; // C++ string object with data copied from string
// literal - almost always what you *really* want
关于c++ - 指向 const char 与 char 数组与 std::string 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393291/