码迷,mamicode.com
首页 > 系统相关 > 详细

Linux下构造函数string需要注意的问题

时间:2015-06-03 23:00:49      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

/*下面一段程序中,在named类中设置了两个构造函数,分别设置字符串接收方式为string和char*,当n中显示的设定构造为string时,会调用string参数的构造函数,而m中直接传字符串的方式,调用的是char*构造,
在一些C++的教科书中,可能因为编译器的不同而将直接使用字符串常量构造的行为写成调用string构造,而在G++编译下测试为采用char*构造,需要注意下这个小问题*/


1
#include <iostream> 2 #include <stdlib.h> 3 using namespace std; 4 5 template <typename T> 6 7 class named 8 { 9 string name; 10 T n; 11 public: 12 named(const char * ch,const T& b) 13 { 14 name = ch; 15 n = b; 16 cout<<"called char*"<<endl; 17 } 18 named (const string & str, const T &b) 19 { 20 name =str; 21 n =b; 22 cout<<"called string"<<endl; 23 } 24 void print() 25 { 26 cout<<name<<endl; 27 cout<<n<<endl; 28 } 29 30 }; 31 32 int main() 33 { 34 string nam = "hello"; 35 named <int> n(nam,32); 36 named <int> m("hello aaa",32); 37 n.print(); 38 m.print(); 39 }

程序的输出:

called string
called char*
hello
32
hello aaa
32


------------------
(program exited with code: 0)
Press return to continue

 

Linux下构造函数string需要注意的问题

标签:

原文地址:http://www.cnblogs.com/wystan/p/4550307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!