C++ 類型系統
文章推薦指數: 80 %
類型的一些範例包括 int 儲存整數值、 double 儲存浮點值(也稱為純量資料類型) ,或標準程式庫類別std::basic_string 來儲存文字。
您可以藉由定義 ...
跳到主要內容
已不再支援此瀏覽器。
請升級至MicrosoftEdge,以利用最新功能、安全性更新和技術支援。
下載MicrosoftEdge
其他資訊
目錄
結束焦點模式
語言
閱讀英文
儲存
目錄
閱讀英文
儲存
意見反應
編輯
Twitter
LinkedIn
Facebook
電子郵件
目錄
C++typesystem
發行項
11/11/2021
閱讀時間13分鐘
10位參與者
本文內容
TheconceptoftypeisveryimportantinC++.Everyvariable,functionargument,andfunctionreturnvaluemusthaveatypeinordertobecompiled.Also,everyexpression(includingliteralvalues)isimplicitlygivenatypebythecompilerbeforeitisevaluated.Someexamplesoftypesincludeinttostoreintegervalues,doubletostorefloating-pointvalues(alsoknownasscalardatatypes),ortheStandardLibraryclassstd::basic_stringtostoretext.Youcancreateyourowntypebydefiningaclassorstruct.Thetypespecifiestheamountofmemorythatwillbeallocatedforthevariable(orexpressionresult),thekindsofvaluesthatmaybestoredinthatvariable,howthosevalues(asbitpatterns)areinterpreted,andtheoperationsthatcanbeperformedonit.ThisarticlecontainsaninformaloverviewofthemajorfeaturesoftheC++typesystem.
Terminology
Variable:Thesymbolicnameofaquantityofdatasothatthenamecanbeusedtoaccessthedataitreferstothroughoutthescopeofthecodewhereitisdefined.InC++,variableisgenerallyusedtorefertoinstancesofscalardatatypes,whereasinstancesofothertypesareusuallycalledobjects.
Object:Forsimplicityandconsistency,thisarticleusesthetermobjecttorefertoanyinstanceofaclassorstructure,andwhenitisusedinthegeneralsenseincludesalltypes,evenscalarvariables.
PODtype(plainolddata):ThisinformalcategoryofdatatypesinC++referstotypesthatarescalar(seetheFundamentaltypessection)orarePODclasses.APODclasshasnostaticdatamembersthataren’talsoPODs,andhasnouser-definedconstructors,user-defineddestructors,oruser-definedassignmentoperators.Also,aPODclasshasnovirtualfunctions,nobaseclass,andnoprivateorprotectednon-staticdatamembers.PODtypesareoftenusedforexternaldatainterchange,forexamplewithamodulewrittenintheClanguage(whichhasPODtypesonly).
Specifyingvariableandfunctiontypes
C++isastronglytypedlanguageanditisalsostatically-typed;everyobjecthasatypeandthattypeneverchanges(nottobeconfusedwithstaticdataobjects).Whenyoudeclareavariableinyourcode,youmusteitherspecifyitstypeexplicitly,orusetheautokeywordtoinstructthecompilertodeducethetypefromtheinitializer.Whenyoudeclareafunctioninyourcode,youmustspecifythetypeofeachargumentanditsreturnvalue,orvoidifnovalueisreturnedbythefunction.Theexceptioniswhenyouareusingfunctiontemplates,whichallowforargumentsofarbitrarytypes.
Afteryoufirstdeclareavariable,youcannotchangeitstypeatsomelaterpoint.However,youcancopythevariable’svalueorafunction’sreturnvalueintoanothervariableofadifferenttype.Suchoperationsarecalledtypeconversions,whicharesometimesnecessarybutarealsopotentialsourcesofdatalossorincorrectness.
WhenyoudeclareavariableofPODtype,westronglyrecommendyouinitializeit,whichmeanstogiveitaninitialvalue.Untilyouinitializeavariable,ithasa"garbage"valuethatconsistsofwhateverbitshappenedtobeinthatmemorylocationpreviously.ThisisanimportantaspectofC++toremember,especiallyifyouarecomingfromanotherlanguagethathandlesinitializationforyou.Whendeclaringavariableofnon-PODclasstype,theconstructorhandlesinitialization.
Thefollowingexampleshowssomesimplevariabledeclarationswithsomedescriptionsforeach.Theexamplealsoshowshowthecompilerusestypeinformationtoallowordisallowcertainsubsequentoperationsonthevariable.
intresult=0;//Declareandinitializeaninteger.
doublecoefficient=10.8;//Declareandinitializeafloating
//pointvalue.
autoname="LadyG.";//Declareavariableandletcompiler
//deducethetype.
autoaddress;//error.Compilercannotdeduceatype
//withoutanintializingvalue.
age=12;//error.Variabledeclarationmust
//specifyatypeoruseauto!
result="KennyG.";//error.Can’tassigntexttoanint.
stringresult="zero";//error.Can’tredefineavariablewith
//newtype.
intmaxValue;//Notrecommended!maxValuecontains
//garbagebitsuntilitisinitialized.
Fundamental(built-in)types
Unlikesomelanguages,C++hasnouniversalbasetypefromwhichallothertypesarederived.Thelanguageincludesmanyfundamentaltypes,alsoknownasbuilt-intypes.Thisincludesnumerictypessuchasint,double,long,bool,plusthecharandwchar_ttypesforASCIIandUNICODEcharacters,respectively.Mostintegralfundamentaltypes(exceptbool,double,wchar_t,andrelatedtypes)allhaveunsignedversions,whichmodifytherangeofvaluesthatthevariablecanstore.Forexample,anint,whichstoresa32-bitsignedinteger,canrepresentavaluefrom-2,147,483,648to2,147,483,647.Anunsignedint,whichisalsostoredas32-bits,canstoreavaluefrom0to4,294,967,295.Thetotalnumberofpossiblevaluesineachcaseisthesame;onlytherangeisdifferent.
Thefundamentaltypesarerecognizedbythecompiler,whichhasbuilt-inrulesthatgovernwhatoperationsyoucanperformonthem,andhowtheycanbeconvertedtootherfundamentaltypes.Foracompletelistofbuilt-intypesandtheirsizeandnumericlimits,seeBuilt-intypes.
Thefollowingillustrationshowstherelativesizesofthebuilt-intypesintheMicrosoftC++implementation:
Thefollowingtableliststhemostfrequentlyusedfundamentaltypes,andtheirsizesintheMicrosoftC++implementation:
Type
Size
Comment
int
4bytes
Thedefaultchoiceforintegralvalues.
double
8bytes
Thedefaultchoiceforfloatingpointvalues.
bool
1byte
Representsvaluesthatcanbeeithertrueorfalse.
char
1byte
UseforASCIIcharactersinolderC-stylestringsorstd::stringobjectsthatwillneverhavetobeconvertedtoUNICODE.
wchar_t
2bytes
Represents"wide"charactervaluesthatmaybeencodedinUNICODEformat(UTF-16onWindows,otheroperatingsystemsmaydiffer).Thisisthecharactertypethatisusedinstringsoftypestd::wstring.
unsignedchar
1byte
C++hasnobuilt-inbytetype.Useunsignedchartorepresentabytevalue.
unsignedint
4bytes
Defaultchoiceforbitflags.
longlong
8bytes
Representsverylargeintegervalues.
OtherC++implementationsmayusedifferentsizesforcertainnumerictypes.FormoreinformationonthesizesandsizerelationshipsthattheC++standardrequires,seeBuilt-intypes.
Thevoidtype
Thevoidtypeisaspecialtype;youcannotdeclareavariableoftypevoid,butyoucandeclareavariableoftypevoid*(pointertovoid),whichissometimesnecessarywhenallocatingraw(un-typed)memory.However,pointerstovoidarenottype-safeandgenerallytheiruseisstronglydiscouragedinmodernC++.Inafunctiondeclaration,avoidreturnvaluemeansthatthefunctiondoesnotreturnavalue;thisisacommonandacceptableuseofvoid.WhiletheClanguagerequiredfunctionsthathavezeroparameterstodeclarevoidintheparameterlist,forexample,fou(void),thispracticeisdiscouragedinmodernC++andshouldbedeclaredfou().Formoreinformation,seeTypeConversionsandTypeSafety.
consttypequalifier
Anybuilt-inoruser-definedtypemaybequalifiedbytheconstkeyword.Additionally,memberfunctionsmaybeconst-qualifiedandevenconst-overloaded.Thevalueofaconsttypecannotbemodifiedafteritisinitialized.
constdoublePI=3.1415;
PI=.75//Error.Cannotmodifyconstvariable.
Theconstqualifierisusedextensivelyinfunctionandvariabledeclarationsand"constcorrectness"isanimportantconceptinC++;essentiallyitmeanstouseconsttoguarantee,atcompiletime,thatvaluesarenotmodifiedunintentionally.Formoreinformation,seeconst.
Aconsttypeisdistinctfromitsnon-constversion;forexample,constintisadistincttypefromint.YoucanusetheC++const_castoperatoronthoserareoccasionswhenyoumustremoveconst-nessfromavariable.Formoreinformation,seeTypeConversionsandTypeSafety.
Stringtypes
Strictlyspeaking,theC++languagehasnobuilt-instringtype;charandwchar_tstoresinglecharacters-youmustdeclareanarrayofthesetypestoapproximateastring,addingaterminatingnullvalue(forexample,ASCII'\0')tothearrayelementonepastthelastvalidcharacter(alsocalledaC-stylestring).C-stylestringsrequiredmuchmorecodetobewrittenortheuseofexternalstringutilitylibraryfunctions.ButinmodernC++,wehavetheStandardLibrarytypesstd::string(for8-bitchar-typecharacterstrings)orstd::wstring(for16-bitwchar_t-typecharacterstrings).TheseC++StandardLibrarycontainerscanbethoughtofasnativestringtypesbecausetheyarepartofthestandardlibrariesthatareincludedinanyconformantC++buildenvironment.Simplyusethe#include
延伸文章資訊
- 1C++ 類型系統
類型的一些範例包括 int 儲存整數值、 double 儲存浮點值(也稱為純量資料類型) ,或標準程式庫類別std::basic_string 來儲存文字。 您可以藉由定義 ...
- 25. 類別(Classes) — Google C++ 開源專案風格指南
類別是C++ 中程式碼的基本單元。想當然爾,在程式中類別將被廣泛使用。本節列舉了在撰寫一個類別時該做的和不該做的事項。
- 3C++物件導向及增進效率程式技巧
類別的關鍵字為class,功能. 與C 語言的struct 類似,不過C 語言中的struct 只能包含資料,不能包含函數。 class 宣告的形式如下:. 其中,class_name 是用戶定...
- 4定義類別
從C 背景來的開發者可能會想,這種風格像是C 的結構(struct),在C++ 中, struct 也被視為定義類別,將以上的 class 關鍵字換為 struct ,程式也可以運作, stru...
- 5[物件導向Ep. 1] 類別與物件 - CodiMD
會建議使用C++ 或是Java 當作基底語言去學習,C++ 的原因是他有完整的物件導向特性;Java 也有(甚至有時候還比C++ 更好理解些),只是他的開發環境比較囉嗦;Python 本身是 ...