string 声明语句该怎么写才好?大家来讨论讨论

C++语言 码拜 9年前 (2015-05-11) 999次浏览 0个评论
string str = 0;
string str = NULL;

上面两种错误的写法,错在哪里?

string str = 0;
string str;

这两种写法哪个比较好呢?为什么?

下面的两种写法写错了,请见谅

string str = "0";
string str;
http://www.cplusplus.com/reference/string/string/operator=/index.html

http://www.cplusplus.com/reference/string/string/string/index.html

10分
string 的构造函数不支持 void*指针的传入。所有前两句错了。
string str = “\0”; string str = “”;
这个才是字符串空的写法。
10分
string str = 0;
string str = NULL;
string str=0,string没有定义一个整型的构造函数。所以无法完成隐式转换(将int转换成string)。

string str = “0”;
string str;

string str=”0″先调用string接受(const char*)的构造函数,把”0″隐式转换成string,再调用赋值构造对初始化str。
string str,直接调用string的无参构造函数。

C++中就是这样
string str; 

注意, 不要把Java中的思想带过来了.
在C++中 string str;   就已经是实例化了一个对象, 并且会调用其构造函数初始化.
在Java中string str; 仅是定义了一个引用,没有对象.

在C++中, 如果你想定义时,用其它参数初始化这个对象可以这样.
string  str(“abcdefg”);
或者
string str=”abcdefg”;

10分
string str = 0;
string str = NULL;
在C++中.  NULL == 0
并且string没有重载能接收一个整型数据的构造函数.
10分

string str = 0;
string str = NULL;

这里两种写法其实是一个意思吧,NULL就是0吧,string是不接受NULL值构造的,虽然编译可以通过,但是运行的时候会触发断言

string str = “0”;
这个是调用的是普通构造函数,不是拷贝构造函数啊,我写了代码调试的,进了这个函数:

__CLR_OR_THIS_CALL basic_string(const _Elem *_Ptr)
		: _Mybase()
		{	// construct from [_Ptr, <null>)
		_Tidy();
		assign(_Ptr);
		}

string str;
这个调用的就是默认构造函数了。

引用 4 楼 mxway 的回复:

string str=”0″先调用string接受(const char*)的构造函数,把”0″隐式转换成string,再调用赋值构造对初始化str。
string str,直接调用string的无参构造函数。

更正错误,由于string有(const char *)类型的构造函数,直接调用该类型的构造函数进行隐式转换成string。

明白了,声明string类型的变量就是new一个string类的对象,可以这么理解,看看string的构造函数很有必要
引用 9 楼 CKRGD 的回复:

明白了,声明string类型的变量就是new一个string类的对象,可以这么理解,看看string的构造函数很有必要

通常只要仔细看看zhao4zhong1的回复就足够了。


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明string 声明语句该怎么写才好?大家来讨论讨论
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!