C++ 類型系統

文章推薦指數: 80 %
投票人數:10人

類型的一些範例包括 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#includedirectivetomakethesetypesavailableinyourprogram.(IfyouareusingMFCorATL,theCStringclassisalsoavailable,butisnotpartoftheC++standard.)Theuseofnull-terminatedcharacterarrays(theC-stylestringspreviouslymentioned)isstronglydiscouragedinmodernC++. User-definedtypes Whenyoudefineaclass,struct,union,orenum,thatconstructisusedintherestofyourcodeasifitwereafundamentaltype.Ithasaknownsizeinmemory,andcertainrulesabouthowitcanbeusedapplytoitforcompile-timecheckingand,atruntime,forthelifeofyourprogram.Theprimarydifferencesbetweenthefundamentalbuilt-intypesanduser-definedtypesareasfollows: Thecompilerhasnobuilt-inknowledgeofauser-definedtype.Itlearnsofthetypewhenitfirstencountersthedefinitionduringthecompilationprocess. Youspecifywhatoperationscanbeperformedonyourtype,andhowitcanbeconvertedtoothertypes,bydefining(throughoverloading)theappropriateoperators,eitherasclassmembersornon-memberfunctions.Formoreinformation,seeFunctionOverloading Pointertypes DatingbacktotheearliestversionsoftheClanguage,C++continuestoletyoudeclareavariableofapointertypebyusingthespecialdeclarator*(asterisk).Apointertypestorestheaddressofthelocationinmemorywheretheactualdatavalueisstored.InmodernC++,thesearereferredtoasrawpointers,andareaccessedinyourcodethroughspecialoperators*(asterisk)or->(dashwithgreater-than).Thisiscalleddereferencing,andwhichonethatyouusedependsonwhetheryouaredereferencingapointertoascalarorapointertoamemberinanobject.WorkingwithpointertypeshaslongbeenoneofthemostchallengingandconfusingaspectsofCandC++programdevelopment.Thissectionoutlinessomefactsandpracticestohelpuserawpointersifyouwantto,butinmodernC++it’snolongerrequired(orrecommended)touserawpointersforobjectownershipatall,duetotheevolutionofthesmartpointer(discussedmoreattheendofthissection).Itisstillusefulandsafetouserawpointersforobservingobjects,butifyoumustusethemforobjectownership,youshoulddosowithcautionandverycarefulconsiderationofhowtheobjectsownedbythemarecreatedanddestroyed. Thefirstthingthatyoushouldknowisdeclaringarawpointervariablewillallocateonlythememorythatisrequiredtostoreanaddressofthememorylocationthatthepointerwillbereferringtowhenitisdereferenced.Allocationofthememoryforthedatavalueitself(alsocalledbackingstore)isnotyetallocated.Inotherwords,bydeclaringarawpointervariable,youarecreatingamemoryaddressvariable,notanactualdatavariable.Dereferencingapointervariablebeforemakingsurethatitcontainsavalidaddresstoabackingstorewillcauseundefinedbehavior(usuallyafatalerror)inyourprogram.Thefollowingexampledemonstratesthiskindoferror: int*pNumber;//Declareapointer-to-intvariable. *pNumber=10;//error.Althoughthismaycompile,itis //aseriouserror.Wearedereferencingan //uninitializedpointervariablewithno //allocatedmemorytopointto. Theexampledereferencesapointertypewithouthavinganymemoryallocatedtostoretheactualintegerdataoravalidmemoryaddressassignedtoit.Thefollowingcodecorrectstheseerrors: intnumber=10;//Declareandinitializealocalinteger //variablefordatabackingstore. int*pNumber=&number;//Declareandinitializealocalinteger //pointervariabletoavalidmemory //addresstothatbackingstore. ... *pNumber=41;//Dereferenceandstoreanewvaluein //thememorypointedtoby //pNumber,theintegervariablecalled //"number".Note"number"waschanged,not //"pNumber". ThecorrectedcodeexampleuseslocalstackmemorytocreatethebackingstorethatpNumberpointsto.Weuseafundamentaltypeforsimplicity.Inpractice,thebackingstoreforpointersaremostoftenuser-definedtypesthataredynamically-allocatedinanareaofmemorycalledtheheap(orfreestore)byusinganewkeywordexpression(inC-styleprogramming,theoldermalloc()Cruntimelibraryfunctionwasused).Onceallocated,thesevariablesareusuallyreferredtoasobjects,especiallyiftheyarebasedonaclassdefinition.Memorythatisallocatedwithnewmustbedeletedbyacorrespondingdeletestatement(or,ifyouusedthemalloc()functiontoallocateit,theCruntimefunctionfree()). However,itiseasytoforgettodeleteadynamically-allocatedobject-especiallyincomplexcode,whichcausesaresourcebugcalledamemoryleak.Forthisreason,theuseofrawpointersisstronglydiscouragedinmodernC++.Itisalmostalwaysbettertowraparawpointerinasmartpointer,whichwillautomaticallyreleasethememorywhenitsdestructorisinvoked(whenthecodegoesoutofscopeforthesmartpointer);byusingsmartpointersyouvirtuallyeliminateawholeclassofbugsinyourC++programs.Inthefollowingexample,assumeMyClassisauser-definedtypethathasapublicmethodDoSomeWork(); voidsomeFunction(){ unique_ptrpMc(newMyClass); pMc->DoSomeWork(); } //Nomemoryleak.Out-of-scopeautomaticallycallsthedestructor //fortheunique_ptr,freeingtheresource. Formoreinformationaboutsmartpointers,seeSmartPointers. Formoreinformationaboutpointerconversions,seeTypeConversionsandTypeSafety. Formoreinformationaboutpointersingeneral,seePointers. Windowsdatatypes InclassicWin32programmingforCandC++,mostfunctionsuseWindows-specifictypedefsand#definemacros(definedinwindef.h)tospecifythetypesofparametersandreturnvalues.TheseWindowsdatatypesaremostlyjustspecialnames(aliases)giventoC/C++built-intypes.Foracompletelistofthesetypedefsandpreprocessordefinitions,seeWindowsDataTypes.Someofthesetypedefs,suchasHRESULTandLCID,areusefulanddescriptive.Others,suchasINT,havenospecialmeaningandarejustaliasesforfundamentalC++types.OtherWindowsdatatypeshavenamesthatareretainedfromthedaysofCprogrammingand16-bitprocessors,andhavenopurposeormeaningonmodernhardwareoroperatingsystems.TherearealsospecialdatatypesassociatedwiththeWindowsRuntimeLibrary,listedasWindowsRuntimebasedatatypes.InmodernC++,thegeneralguidelineistoprefertheC++fundamentaltypesunlesstheWindowstypecommunicatessomeadditionalmeaningabouthowthevalueistobeinterpreted. Moreinformation FormoreinformationabouttheC++typesystem,seethefollowingtopics. ValueTypes Describesvaluetypesalongwithissuesrelatingtotheiruse. TypeConversionsandTypeSafety Describescommontypeconversionissuesandshowshowtoavoidthem. Seealso WelcomebacktoC++ C++LanguageReference C++StandardLibrary 意見反應 提交並檢視相關的意見反應 本產品 本頁 檢視所有頁面意見反應 本文內容



請為這篇文章評分?