Template class generate errors in C++
这个程序没有编译。怎么了?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include<iostream> #include<map> using namespace std; template<class T>class Data{ string header; T data; public: Data(string h, T d){header = h, data = d;} void WriteData() { cout<<header<<":"<<data<<endl; } }; int main(int argc, _TCHAR* argv[]) { Data<int> idata("Roll", 100); Data<string>sdata("Name","Jakir"); idata.WriteData(); sdata.WriteData(); return 0; } |
显示以下错误。
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 10.0\vc\include\ostream(679): could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<>(std::basic_ostream<_Elem,_Traits> &,const char *)'
with
[
_Elem=char,
_Traits=std::char_traits
]while trying to match the argument list '(std::ostream, std::string)'
.....\maptest\mapt\mapt\mapt.cpp(16) : while compiling class template member function 'void Data::WriteData(void)'
with
[
T=int
]
你好像忘了:
1 | #include <string> |
您不能指望传递包含所有必要的头文件,因为其他头文件(如
如果您使用的是
接受
此外,避免在全局命名空间范围内使用
1 | using namespace std; |
它们很容易导致名称冲突,通常被认为是一种糟糕的编程实践。
t_char的类型不正确,因为argv应该有一个类型,例如char*
正确的源代码是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include<iostream> #include<map> #include<string> using namespace std; template<class T>class Data{ string header; T data; public: Data(string h, T d){header = h, data = d;} void WriteData() { cout<<header<<":"<<data<<endl; } }; int main(int argc, char* argv[]) { Data<int> idata("Roll", 100); Data<string>sdata("Name","Jakir"); idata.WriteData(); sdata.WriteData(); return 0; } |