您的位置:首页 > 编程语言 > C语言/C++

C++11特性(01)auto关键字

2015-06-14 08:03 519 查看

C++11特性之一:auto关键字

auto关键字

在C++11之前的版本中,其实也有auto关键字(这个关键字其实是为了兼容C语言中的auto自动变量),所以在C语言中也可以使用auto关键字,只是此时的auto的意思就不是C++11中的特性:自动类型。
如:
auto ai = 33;         //ai类型为int

auto ad = 3.221;      //ad类型为double

auto str = "Hello World";    //str类型为const char *
std::cout << "ai = " << ai << " ad = " << ad << " str = " << str << std::endl;


这个在Cocos3.X版本中使用最多,方便我们用户去进行类型的书写,代码量也相应减少。

这个特性我们在编写MFC程序的时候也可以使用:如
// 修改此代码以绘制文档数据
dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));

auto strText = _T("TODO: implement thumbnail drawing here");                          //strText类型为CString
LOGFONT lf;

auto pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));   //pDefaultGUIFont的类型为CFont
pDefaultGUIFont->GetLogFont(&lf);
lf.lfHeight = 36;

auto fontDraw;
fontDraw.CreateFontIndirect(&lf);

auto pOldFont = dc.SelectObject(&fontDraw);
dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK);
dc.SelectObject(pOldFont);
这样的话,极大的方便了我们去编写程序,并且也不用以前的的从派生类到基类的转换等等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ class C++11