在学习C++入门时遇到了一些问题,现在总结一下,希望对后学者有所帮助。
虽然vc6.0现在来说有点过时,但是问题的解决思路是可以借鉴的。下面说一下string类型和exception类型的使用。
通常情况下使用这两种类型,会报一些错误,比如下面这些:
1> error C2065: 'out_of_range' : undeclared identifier
2> error C2065: 'string' : undeclared identifier
3> error C2784: 'class std::reverse_iterator<_RI,_Ty,_Rt,_Pt,_D> __cdecl std::operator +(_D,const class std::reverse_iterator<_RI,_Ty,_Rt,_Pt,_D> &)' : could not deduce template argument for '' from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >'
4> error C2676: binary '+' : 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' does not define this operator or a conversion to a type acceptable to the predefined operator Error executing cl.exe.
下面分析原因:
1>和2>需要包含头文件<xstring>和 <stdexcept>,并且加上【using namespace std;】这句话才可以,因为定义的string和exception都在namespace std中。
3>和4>是因为string没有定义operator+这个操作符,自己定义一下就可以(我是自己定义的,可能有系统定义好的)。
下面附上参考代码:
#include <iostream.h>
#include <xstring>
#include <stdexcept>
#include <typeinfo>
using namespace std;
class A
{
public:
A(){}
A(string s){str = s;}
const char* what()const throw()
{
return str.c_str();
}
string str;
};
string operator+(string s1, string s2)
{
string s = s1;
s += s2;
return s;
}
void main()
{
try
{
A a("abcd");
cout<<a.what()<<endl;
string s, s1("AB"), s2("CD");
s = s1 + s2;
cout<<s1.c_str()<<endl;
cout<<s2.c_str()<<endl;
cout<<s.c_str()<<endl;
throw out_of_range("abc");
}
catch (exception &e)
{
cout<<typeid(e).name()<<endl;
cout<<e.what()<<endl;
}
}
输出结果如下:
abcd
AB
CD
ABCD
class std::out_of_range
abc
Press any key to continue
说明一下,上面的抛出异常和string相加完全是为了演示异常和string在vc中如何使用,并没有实际的意义。