如何C ++隐式转换c样式字符串为字符串对象? [英] how C++ Implicitly convert c style string to a string object?

查看:105
本文介绍了如何C ++隐式转换c样式字符串为字符串对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  string s =abc; 

上述语句将首先调用 string(const char * s) code>构造函数,然后根据调用复制构造函数是C ++中字符串初始化的区别吗?
这里是问题:C ++如何知道应该调用 string(const char * s)将字符串abc转换为临时字符串对象? p>

注意
复制初始化时不会调用复制构造函数。

使用语法初始化对象

  string s =abc 

称为复制初始化



有几种情况是合法的初始化。在所有情况下,RHS必须可转换为 string 才能正常工作。



一个字符串文字可以转换为 string 是通过 string 的构造函数获取 char const * 。这称为用户定义的转化


string s = "abc";

The above statement will first invoke string ( const char * s ) constructor, then invoke copy constructor according to What are the differences in string initialization in C++? . Here is the question: how C++ know it should invoke string ( const char * s ) to convert literal string "abc" to a temporary string object?

Note: copy constructor won't be invoked in copy initialization.

解决方案

Initializing an object by using the syntax

string s = "abc";

is called copy initialization.

There are several scenarios where that is legal initialization. In all cases the RHS must be convertible to a string for it to work.

One way a string literal can be converted to a string is through the constructor of string that takes a char const*. That is called a user defined conversion.

这篇关于如何C ++隐式转换c样式字符串为字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆