Linux、Windows下错误码查看与错误原因格式化输出
Windows下:
C++**的类型转换函数**
使用GetLastError()获得错误码,通过FormatMessage API获得错误码对应的出错信息,
reinterpret_cast、const_cast、static_cast和dynamic_cast 前三个类型转换是在编译时实现转换,dynamic_cast是在运行时进行类型转换的。
HLOCAL pBuffer = NULL; //系统缓冲区指针
int nId = GetDlgItemInt(IDC_EDIT1); //错误码
reinterpret_cast<new type>(expression)
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, nId, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
reinterpret_cast<LPTSTR>(&pBuffer), 0, NULL);
//MAKELANGID(LANG_ENGLISH,
SUBLANG_ENGLISH_US)将出错信息的输出语言设为英文
//reinterpret_cast告诉编译器,把待转换的类型当作目标类型处理(实际上并不执行转换)
const_cast< new type>( expression)
SetDlgItemText(IDC_REDIT, static_cast<LPTSTR>(::LocalLock(pBuffer)));
static_cast<new type>(expression)
::LocalFree(pBuffer); //释放系统缓冲区
dynamic_cast<newtype>(expression)
Linux下:
#include <errno.h>
1**、**reinterpret_cast
使用errno错误码,并通过strerror(errno)获得错误码对应的出错信息
reinterpret_cast**将一个类型的指针转换为另一个类型的指针,**它也允许从一个指针转换为整数类型。这种转换不用修改指针变量值数据存放格式(不改变指针变量),而是在编译时重新解释指针的类型(操作结果只是简单的从一个指针到别的指针的值的二进制拷贝。在类型之间指向的内容不做任何类型的检查和转换)。但不能用于非指针类型的转换。
(1)转换一个指针为其它类型的指针,能够在非相关的类型之间转换
class A {};
class B {};
A * a = new A;
B * b = reinterpret_cast<B *>(a);
(2)不能将const指针转换为非const
const int* point =&j;
dm =reinterpret_cast<double*>(point);
(3)不能用于非指针类型的转换
int i; double j = 2.1;
j =reinterpret_cast<int>(j);
(4)可以将一段buffer转成一个类的对象指针,或者反过来。
class A;
A a;
char* pBuffer = reinterpret_cast<char*> (&a);
2**、**const_cast
const_cast用于const**指针与普通指针间的相互转换(将一个const指针转换为对应指针类型的普通指针变量,也可以将一个普通指针变量转换为一个const指针)。不能将非常量指针变量转换为普通变量**(从const转为非const,或者volatile转为非volatile)。
本文由宝马娱乐在线城发布于互联网络,转载请注明出处:Linux、Windows下错误码查看与错误原因格式化输出
关键词: