[英]Why don't we need objects to store string data?
In C++, if string is a class, why do we not need the dot operator or an object to store data in a string? 在C ++中,如果string是一个类,为什么我们不需要点运算符或对象来将数据存储在字符串中?
Classic string: 经典字符串:
string str = "ABC";
Why can we directly pass ABC using " " instead of doing it like 为什么我们可以使用“”直接传递ABC而不是像它那样
string str;
str.data = "ABC";
But we need to use objects to access the functions. 但是我们需要使用对象来访问这些函数。 Example:
例:
str.length();
Why do we do this? 我们为什么要做这个?
Is string some special kind of class? 字符串是一类特殊的类吗?
string str = "ABC";
is not assignment. 不是任务。 It is construction.
这是建筑。 Specifically it calls the
std::string
constructor taking a const char *
argument. 具体来说,它调用
std::string
构造函数来获取const char *
参数。
It's the same as doing 这跟做的一样
string str("ABC");
just different syntax. 只是不同的语法。
Assignment also works. 作业也有效。 You do this:
你做这个:
string str;
str = "ABC";
See also: 也可以看看:
std::basic_string has a constructor like this: std :: basic_string有一个这样的构造函数:
basic_string( const CharT* s, const Allocator& alloc = Allocator() );
Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s.
构造字符串,其内容使用s指向的以null结尾的字符串的副本进行初始化。
But the important point to note is that this constructor is not explicit
, thus the compiler can do implicit conversion of null terminated character string during constructor call. 但需要注意的重要一点是,此构造函数不是
explicit
,因此编译器可以在构造函数调用期间对空终止字符串进行隐式转换。
For example, following code compiles without any issue: 例如,以下代码编译时没有任何问题:
class Foo {
public:
Foo(int) {}
};
int main() {
Foo f = 10;
}
It won't compile if the constructor is written as: 如果构造函数被写为:
explicit Foo(int) {}
In C++ a string literal is not a std::string
, but a C style character array( char[N]
). 在C ++中 ,字符串文字不是
std::string
,而是C样式字符数组( char[N]
)。 And yes std::string
or any other 3rd party string type that you may see is a class with a converting constructor accepting character arrays as input. 是的
std::string
或任何其他第三方字符串类型,您可能会看到一个类,其转换构造函数接受字符数组作为输入。 More precisely, std::string
is a type alias for an instansiation of the template std::basic_string
. 更确切地说,
std::string
是模板 std::basic_string
的实例化的类型别名 。 In short words, before you can do anything with a string literal, you'd better convert it to a string: 简而言之,在使用字符串文字做任何事情之前,最好将其转换为字符串:
std::string{"ABC"}.size()
Or you will have to switch to C API which is not recommended for beginners: 或者您必须切换到不适合初学者的C API:
strlen( "ABC")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.