/*下面一段程序中,在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