奇怪的string

代码1:

 1 #include <iostream>
 2 //#include <string>
 3 using namespace std;
 4 
 5 int main(int argc, char **argv)
 6 {
 7     string s = "hello world!";
 8     //cout << s << endl;
 9     return 0;
10 }

这段代码仅仅是定义了string,而没有使用它,可以编译通过,正常运行。推测原因是:间接包含了string的定义,因此仅仅用来定义是可以的,但是有点讲不通的是,一般这种类似于预定义的情况,只能定义该类型的指针或者引用。不能定义它本身的变量的。所以,此处是疑问1.

代码2:

 1 #include <iostream>
 2 //#include <string>
 3 using namespace std;
 4 
 5 int main(int argc, char **argv)
 6 {
 7     string s = "hello world!";
 8     cout << s << endl;
 9     return 0;
10 }

这段代码编译不过。我的理解是,使用了此变量,但是没哟包含头文件,所以编译不过很合理,但是结合下一段代码来看,就有点奇怪了。

代码3:

 1 #include <iostream>
 2 //#include <string>
 3 using namespace std;
 4 
 5 int main(int argc, char **argv)
 6 {
 7     string s = "hello world!";
 8     cout << s.c_str() << endl;
 9     return 0;
10 }

这段代码可以编译过并正常执行。这里与上一段代码唯一的区别就是输出时先将string转换为了字符串类型。这里是疑问2.

代码4:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 int main(int argc, char **argv)
 6 {
 7     string s = "hello world!";
 8     cout << s << endl;
 9     return 0;
10 }

这段代码可以编译通过并正常执行。这里结果也是在意料之中的。

 

综合上面的几种情况,对string的使用还是有一些疑问的,虽然不影响正常使用,但是还是喜欢钻一钻这个问题,打破砂锅问到底。现在自己的知识还解释不了这个问题,只能待自己慢慢积累了。

 

加油吧,少年!

posted @ 2014-10-31 08:55  冷冰若水  阅读(172)  评论(0)    收藏  举报