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中如何使用,并没有实际的意义。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
VC6.0 解析来自 Web 的 JSON 数据,你可以使用第三方库来实现。由于 VC6.0 是一个较旧的版本,它可能不支持现代的 JSON 解析器。以下是一种可能的解决方案: 1. 首先,你需要下载并集成一个适用于 VC6.0 的 JSON 解析库。例如,你可以尝试使用 cJSON(https://github.com/DaveGamble/cJSON)或 JSON for Modern C++(https://github.com/nlohmann/json)。 2. 下载所选库的源代码,并将其添加到你的 VC6.0 项目。确保将头文件和源文件正确地添加到项目。 3. 在你的代码,包含所选库的头文件,并使用其提供的 API 进行 JSON 解析。具体的步骤和函数将取决于你选择的库。 下面是使用 cJSON 库解析 JSON 数据的一个简单示例: ```c #include <stdio.h> #include <stdlib.h> #include "cJSON.h" int main() { const char* json_string = "{\"name\": \"John\", \"age\": 30}"; cJSON* root = cJSON_Parse(json_string); if (root == NULL) { printf("Error parsing JSON!\n"); return 1; } cJSON* name = cJSON_GetObjectItem(root, "name"); if (name == NULL || !cJSON_IsString(name)) { printf("Error retrieving 'name' from JSON!\n"); cJSON_Delete(root); return 1; } printf("Name: %s\n", name->valuestring); // Clean up cJSON_Delete(root); return 0; } ``` 注意,以上代码仅为示例,具体的解析步骤和函数可能因所选库而异。你需要根据你的实际需求和所选库的文档进行相应的修改。 希望这能帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值