C++c 类型型转换

您现在的位置:&&>>&&>>&&>>&&>>&&>>&正文
&&►&&C++中四种类型转换运算符的使用方法
C++中四种类型转换运算符的使用方法
作者:&&&&阅读人次:……&&&&文章来源:本站原创&&&&发布时间:&&&&
原帖及讨论:
C++的四个类型转换运算符已经有很久了,但一直没有弄清楚它们的用法,今天看到一本书上的解释,才大致地的了解了其具体的用法.具体归纳如下:reinterpret_cast该函数将一个类型的指针转换为另一个类型的指针.这种转换不用修改指针变量值存放格式(不改变指针变量值),只需在编译时重新解释指针的类型就可做到.reinterpret_cast 可以将指针值转换为一个整型数,但不能用于非指针类型的转换.例://基本类型指针的类型转换double d=9.2;double* pd = &d;int *pi = reinterpret_cast&int*&(pd);&&//相当于int *pi = (int*)//不相关的类的指针的类型转换class A{};class B{};A* pa = new A;B* pb = reinterpret_cast&B*&(pa);&&&//相当于B* pb = (B*)//指针转换为整数long l = reinterpret_cast&long&(pi);&&&//相当于long l = (long)const_cast该函数用于去除指针变量的常量属性,将它转换为一个对应指针类型的普通变量。反过来,也可以将一个非常量的指针变量转换为一个常指针变量。这种转换是在编译期间做出的类型更改。例:const int* pci = 0;int* pk = const_cast&int*&(pci);&&//相当于int* pk = (int*)const A* pca = new A;A* pa = const_cast&A*&(pca);&&&&&//相当于A* pa = (A*)出于安全性考虑,const_cast无法将非指针的常量转换为普通变量。static_cast该函数主要用于基本类型之间和具有继承关系的类型之间的转换。这种转换一般会更改变量的内部表示方式,因此,static_cast应用于指针类型转换没有太大意义。例://基本类型转换int i=0;double d = static_cast&double&(i);&&//相当于 double d = (double)i;//转换继承类的对象为基类对象class Base{};class Derived : public Base{};DBase b = static_cast&Base&(d);&&&&&//相当于 Base b = (Base)d;dynamic_cast它与static_cast相对,是动态转换。这种转换是在运行时进行转换分析的,并非在编译时进行,明显区别于上面三个类型转换操作。该函数只能在继承类对象的指针之间或引用之间进行类型转换。进行转换时,会根据当前运行时类型信息,判断类型对象之间的转换是否合法。dynamic_cast的指针转换失败,可通过是否为null检测,引用转换失败则抛出一个bad_cast异常。例:class Base{};class Derived : public Base{};//派生类指针转换为基类指针Derived *pd = new DBase *pb = dynamic_cast&Base*&(pd);if (!pb)&&&&cout && "类型转换失败" &&//没有继承关系,但被转换类有虚函数class A(virtual ~A();)&&&//有虚函数class B{}:A* pa = new A;B* pb&&= dynamic_cast&B*&(pa);如果对无继承关系或者没有虚函数的对象指针进行转换、基本类型指针转换以及基类指针转换为派生类指针,都不能通过编译。&
文章录入:静夜思&&&&责任编辑:静夜思&
上一篇文章: 下一篇文章:
24小时热门帖子
| && | && | && | && | &&|用心创造滤镜
扫码下载App
汇聚2000万达人的兴趣社区下载即送20张免费照片冲印
扫码下载App
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(3891)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'C++类型转换运算符重载',
blogAbstract:'&&&&& 一般来说,类对象的类型转换可由构造函数和转换函数说明。这种转换常称为用户定义的类型转换或类类型转换。C++支持四种类型转换,标准类型-》标准类型,标准类型--&类类型,类类型--&标准类型,类类型--&类类型。标注类型是除了class,struct,union之外的所有其他类型。1.标准类型转换为类类型可通过自定义重载赋值号“=”和构造函数实现#include &iostream&#include &stdlib.h&#include &string.h&class INTEGER{&&&public:',
blogTag:'',
blogUrl:'blog/static/4',
isPublished:1,
istop:false,
modifyTime:4,
publishTime:1,
permalink:'blog/static/4',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}收藏,3.2k 浏览
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
char* askForAString(void)
char temp[16] = &&; //这里是第81行
//scanf(&%s&, temp);
//fflush(stdin);
}char password[16] = &evlos&;
char inputpsw[16];
inputpsw = askForAString(); //这里是第100行
if (strcmp(password, inputpsw) == 0)
printf(&Allowed!&);
}projectv0.cpp: In function ‘char* askForAString()’:projectv0.cpp:81: warning: address of local variable ‘temp’ returnedprojectv0.cpp:100: error: incompatible types in assignment of ‘char*’ to ‘char [16]’请问如何修改才能让程序正常运行?
再请问 “warning: address of local variable ‘temp’ returned” 这个错误是怎么产生应该如何避免呢?谢谢啦 =w=
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
#include &iostream&
#include &list&
#include &string&
std::string askForAString(void)
getline(std::cin, temp);
int main(int argc, char* argv)
std::string password(&evlos&);
if ( 0 == pare(askForAString()) ) {
std::cout && &OK& && std::
system(&pause&);
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
char* askForAString(void)
// 这里是申请的全局的动态内存
char * temp = (char *)malloc(sizeof(char)*16)
//scanf(&%s&, temp);
//fflush(stdin);
}char password[16] = &evlos&;
char inputpsw[16];
inputpsw = askForAString(); //这里是第100行
if (strcmp(password, inputpsw) == 0)
printf(&Allowed!&);
free(inputpsw)
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
第一个函数的栈内存返回了。。。问题不在返回上,问题在分配上。分配内存的语句是char temp[16] = &&;temp数组是局部变量,局部变量是分配在栈上的。一个函数返回时,他的栈空间就会被释放了。要养成良好的内存管理习惯:面向过程的方法中建议,在A方法分配的内存就在A方法释放;面向对象编程中建议A对象初始化的内存由A对象释放。而在第一个函数中用malloc分配内存(malloc在堆上分配)虽不会崩溃或者warning,但是不推荐。因为第一个函数作为内存分配者,却没能承担释放的责任(此责任转交给第二个函数了)。如果还有函数3,函数4...函数100调用函数1,难道要函数2至函数100中都写个free(xxx)吗?如果有函数10000需要从函数100中返回字符串呢?工程大了以后,这样的代码很难维护。我建议:C式编程管理裸奔内存,在方法二上分配buffer,buffer指针作为参数传递给方法一。方法二上用完buffer后及时释放。C++式编程,字符串由对象管理,参考小龙的回答。如果楼主对我的答案投票+1我会很感激
同步到新浪微博
分享到微博?
与我们一起探索更多的未知
专业的开发者技术社区,为用户提供多样化的线上知识交流,丰富的线下活动及给力的工作机会
加入只需一步
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
举报理由:
推广(招聘、广告、SEO 等)方面的内容
带有人身攻击、辱骂、仇恨等违反条款的内容
与已有问题重复(请编辑该提问指向已有相同问题)
不友善内容
答非所问,不符合答题要求
其他原因(请补充说明)
补充说明:
扫扫下载 App
SegmentFault
一起探索更多未知在C++中经常涉及字符串类型转换,VC++里面尤其严重,实在搞不通微软为什么要搞这么多的字符串类型,实在是纠结,这里做一个简单的小总结:从 char * 转换示例说明此示例演示如何从 char * 转换为上面列出的其他字符串类型。// convert_from_char.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
using namespace S
int main()
char *orig = &Hello, World!&;
cout && orig && & (char *)& &&
// Convert to a wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L& (wchar_t *)&);
wcout && wcstring &&
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += & (_bstr_t)&;
cout && bstrt &&
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L& (CComBSTR)&) == S_OK)
CW2A printstr(ccombstr);
cout && printstr &&
// Convert to a CString
CString cstring(orig);
cstring += & (CString)&;
cout && cstring &&
// Convert to a basic_string
string basicstring(orig);
basicstring += & (basic_string)&;
cout && basicstring &&
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += & (System::String)&;
Console::WriteLine(&{0}&, systemstring);
}输出Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)从 wchar_t * 转换示例说明此示例演示如何从 wchar_t * 转换为上面列出的其他字符串类型。// convert_from_wchar_t.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
using namespace S
int main()
wchar_t *orig = L&Hello, World!&;
wcout && orig && L& (wchar_t *)& &&
// Convert to a char*
size_t origsize = wcslen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
char nstring[newsize];
wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE);
strcat_s(nstring, & (char *)&);
cout && nstring &&
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += & (_bstr_t)&;
cout && bstrt &&
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L& (CComBSTR)&) == S_OK)
CW2A printstr(ccombstr);
cout && printstr &&
// Convert to a CString
CString cstring(orig);
cstring += & (CString)&;
cout && cstring &&
// Convert to a basic_string
wstring basicstring(orig);
basicstring += L& (basic_string)&;
wcout && basicstring &&
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += & (System::String)&;
Console::WriteLine(&{0}&, systemstring);
}输出Hello, World! (wchar_t *)
Hello, World! (char *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)从 _bstr_t 转换示例说明此示例演示如何从 _bstr_t 转换为上面列出的其他字符串类型。// convert_from_bstr_t.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
using namespace S
int main()
_bstr_t orig(&Hello, World!&);
wcout && orig && & (_bstr_t)& &&
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, (char *)orig);
strcat_s(nstring, & (char *)&);
cout && nstring &&
// Convert to a wchar_t*
wchar_t wcstring[newsize];
wcscpy_s(wcstring, (wchar_t *)orig);
wcscat_s(wcstring, L& (wchar_t *)&);
wcout && wcstring &&
// Convert to a CComBSTR
CComBSTR ccombstr((char *)orig);
if (ccombstr.Append(L& (CComBSTR)&) == S_OK)
CW2A printstr(ccombstr);
cout && printstr &&
// Convert to a CString
CString cstring((char *)orig);
cstring += & (CString)&;
cout && cstring &&
// Convert to a basic_string
string basicstring((char *)orig);
basicstring += & (basic_string)&;
cout && basicstring &&
// Convert to a System::String
String ^systemstring = gcnew String((char *)orig);
systemstring += & (System::String)&;
Console::WriteLine(&{0}&, systemstring);
}输出Hello, World! (_bstr_t)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)从 CComBSTR 转换示例说明此示例演示如何从 CComBSTR 转换为上面列出的其他字符串类型。// convert_from_ccombstr.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
#include &vcclr.h&
using namespace S
using namespace System::Runtime::InteropS
int main()
CComBSTR orig(&Hello, World!&);
CW2A printstr(orig);
cout && printstr && & (CComBSTR)& &&
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
CW2A tmpstr1(orig);
strcpy_s(nstring, tmpstr1);
strcat_s(nstring, & (char *)&);
cout && nstring &&
// Convert to a wchar_t*
wchar_t wcstring[newsize];
wcscpy_s(wcstring, orig);
wcscat_s(wcstring, L& (wchar_t *)&);
wcout && wcstring &&
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += & (_bstr_t)&;
cout && bstrt &&
// Convert to a CString
CString cstring(orig);
cstring += & (CString)&;
cout && cstring &&
// Convert to a basic_string
wstring basicstring(orig);
basicstring += L& (basic_string)&;
wcout && basicstring &&
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += & (System::String)&;
Console::WriteLine(&{0}&, systemstring);
}输出Hello, World! (CComBSTR)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CString)
Hello, World! (basic_string)
Hello, World! (System::String)从 CString 转换示例说明此示例演示如何从 CString 转换为上面列出的其他字符串类型。// convert_from_cstring.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
using namespace S
int main()
CString orig(&Hello, World!&);
wcout && orig && & (CString)& &&
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, orig);
strcat_s(nstring, & (char *)&);
cout && nstring &&
// Convert to a wchar_t*
// You must first convert to a char * for this to work.
size_t origsize = strlen(orig) + 1;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L& (wchar_t *)&);
wcout && wcstring &&
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += & (_bstr_t)&;
cout && bstrt &&
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L& (CComBSTR)&) == S_OK)
CW2A printstr(ccombstr);
cout && printstr &&
// Convert to a basic_string
string basicstring(orig);
basicstring += & (basic_string)&;
cout && basicstring &&
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += & (System::String)&;
Console::WriteLine(&{0}&, systemstring);
}输出Hello, World! (CString)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (basic_string)
Hello, World! (System::String)从 basic_string 转换示例说明此示例演示如何从 basic_string 转换为上面列出的其他字符串类型。// convert_from_basic_string.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
using namespace S
int main()
string orig(&Hello, World!&);
cout && orig && & (basic_string)& &&
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, orig.c_str());
strcat_s(nstring, & (char *)&);
cout && nstring &&
// Convert to a wchar_t*
// You must first convert to a char * for this to work.
size_t origsize = strlen(orig.c_str()) + 1;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
wcscat_s(wcstring, L& (wchar_t *)&);
wcout && wcstring &&
// Convert to a _bstr_t
_bstr_t bstrt(orig.c_str());
bstrt += & (_bstr_t)&;
cout && bstrt &&
// Convert to a CComBSTR
CComBSTR ccombstr(orig.c_str());
if (ccombstr.Append(L& (CComBSTR)&) == S_OK)
CW2A printstr(ccombstr);
cout && printstr &&
// Convert to a CString
CString cstring(orig.c_str());
cstring += & (CString)&;
cout && cstring &&
// Convert to a System::String
String ^systemstring = gcnew String(orig.c_str());
systemstring += & (System::String)&;
Console::WriteLine(&{0}&, systemstring);
}输出Hello, World! (basic_string)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (System::String)从 System::String 转换示例说明此示例演示如何从 System.String 转换为上面列出的其他字符串类型。// convert_from_system_string.cpp
// compile with /clr /link comsuppw.lib
#include &iostream&
#include &stdlib.h&
#include &string&
#include &atlbase.h&
#include &atlstr.h&
#include &comutil.h&
#include &vcclr.h&
using namespace S
using namespace System::Runtime::InteropS
int main()
String ^orig = gcnew String(&Hello, World!&);
Console::WriteLine(&{0} (System::String)&, orig);
pin_ptr&const wchar_t& wch = PtrToStringChars(orig);
// Convert to a char*
size_t origsize = wcslen(wch) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
char nstring[newsize];
wcstombs_s(&convertedChars, nstring, origsize, wch, _TRUNCATE);
strcat_s(nstring, & (char *)&);
cout && nstring &&
// Convert to a wchar_t*
wchar_t wcstring[newsize];
wcscpy_s(wcstring, wch);
wcscat_s(wcstring, L& (wchar_t *)&);
wcout && wcstring &&
// Convert to a _bstr_t
_bstr_t bstrt(wch);
bstrt += & (_bstr_t)&;
cout && bstrt &&
// Convert to a CComBSTR
CComBSTR ccombstr(wch);
if (ccombstr.Append(L& (CComBSTR)&) == S_OK)
CW2A printstr(ccombstr);
cout && printstr &&
// Convert to a CString
CString cstring(wch);
cstring += & (CString)&;
cout && cstring &&
// Convert to a basic_string
wstring basicstring(wch);
basicstring += L& (basic_string)&;
wcout && basicstring &&
}输出Hello, World! (System::String)
Hello, World! (char *)
Hello, World! (wchar_t *)
Hello, World! (_bstr_t)
Hello, World! (CComBSTR)
Hello, World! (CString)
Hello, World! (basic_string)转自:

我要回帖

更多关于 c 自动类型转换 的文章

 

随机推荐