string和exception在vc6.0中的使用

    在學習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中如何使用,並沒有實際的意義。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章