Visual C++ Tutorial文档格式.docx
《Visual C++ Tutorial文档格式.docx》由会员分享,可在线阅读,更多相关《Visual C++ Tutorial文档格式.docx(24页珍藏版)》请在冰点文库上搜索。
Thoughyouthinkyouwanttodiverightintothecode,youreallydon'
t.Windowsprogrammingisoverwhelmingatfirst.Let'
stakeaquicklookathowWindowsworks.Thebackboneofallofyourprogrammingwillberespondingtoandsendingmessages.Whataremessages?
Messagesaresimplya32bitnumberdesignatingsomeevent.Example:
Youmovethemouse,amessage(definedasWM_MOUSEMOVE)is'
posted'
totheactivewindow.Youpressakey,amessage(WM_KEYDOWN)is'
totheactivewindow.Youresizethewindow,amessage(WM_SIZE)is'
totheactivewindow.Getthepicture?
Nowwheredothesemessagesgo?
Theygetqueuedupandawindoweventuallytakesthemoutofthequeueandreactstothem.ForinstancewhenawindowgetstheWM_MOVEmessageitchangesthecoordinatesofthewindowandredrawsitonthescreen.
Let'
smoveontoHandles.Windowsisverymuchobjectoriented.Youhaveseveralwindowobjects(likethedesktop,theprogramyourreadingthiswith,etc...).Howdoestheprogrammerdistinguishallofthesethingsinannon-object-orientedlanguage?
Heuseshandles.
Handlesareawaytoreferencedifferentwindowsobjects.Youcanhavehandlestowindows,handlestofiles,handlestoallocatedmemory,handlestoimages,etc.
Youcanthinkofthemaspointers.Youmustcreatethemsomehow.Andwhenyouaredonewiththem,youmustdestroythem.Ifyoudon'
tyouwillendupwithwhatiscalledaresourceleak.Thiscouldbringyoursystemtoagrindinghalt.Sotakecaretoalwaysmakesuretheyaredestroyedatsometime.
Nowletstiethesetwothingstogether.
Sayyouhaveawindow.Youwillhaveahandletoit(calledanHWND).Letsnameyourhandleyour_HWND.Theoperatingsystemwantstotellyoutoredrawyourwindowbecauseitwasjustuncoveredbysomeotherwindow.Windozepassesyouamessagelikethis:
PostMessage(your_HWND,WM_PAINT,0,0);
Thisfunctionpostsapaintmessagestothewindowwithhandleyour_HWND.Thelasttwoparametersareusedforextrainformationaboutthemessage.Don'
tworryaboutthemfornow.
Nowyourapplicationwillhaveafunctionwithabigcasestatementinittohandleallofthemessages.Forexample:
void
HandleTheMessage(longMessage)
{
switch(Message)
{
caseWM_PAINT:
DrawWindow();
break;
caseWM_KEYDOWN:
etc...
}
}
Okthatisbasicallyhowwindowsworksunderthehood.ThatshouldbeenoughtogetyougoingwhenwestarttalkingaboutMFC.
IfyouwanttouseMicrosoftVisualC++,ithelpsatonifyoureallyknowC++.Everythingisaboutclasses.IfyouareusedtoplainC,youwon'
treallyseethebigdealwithclassesuntilyouusethemforawhile.Let'
sreviewwhatyouneedtoknowaboutclassestogetstartedwithVC++.
Aclassisastructureforthemostpart.Let'
sworkwithanexampleinsteadofmejusttellingyourules.Let'
smakeaclasstorepresentaline.Inthe.hfileyouwoulddefinetheclassasfollows:
classCLine
intm_nX1;
intm_nY1;
intm_nX2;
intm_nY2;
public:
//constructors
CLine();
CLine(intx1,inty1,intx2,inty2);
//destructor
~CLine();
//setthelinedata
voidSetPoints(intx1,inty1,intx2,inty2);
//drawtheline
voidDraw();
Aquickwordaboutnamingconventions.Classnamesusuallystartwith'
C'
andthemembervariablesusuallyareprefixedbya'
m_'
.Theninthemicrosoftwayyouwillhavealettertoletyouknowwhatdatatypethenameisandthenthenameofthevariable.Capitalizetheletterofallnewwordsinthename.Don'
tuseunderscoresandstufflikethat.Youmayhavethefalsebeliefthatyourcodingstyleisbetter.FromexperienceIcantellyouthatthemicrosoftwayistheway.Itmakesthingseasytoreadandeasytoremembernames(evenwhenitissomeoneelse'
scode).Ifyouseem_pPoint,youwouldassumethisisamembervariableofaclassthatpoints(itisapointer)toapoint.IfyouseefData,youwouldassumethatitisafloating-pointvalue.
Backtoourclass.Theintvariablesaretheendpointsoftheline.Notethattheyarebeforethe'
'
part.Thismeansthataprogrammerusingthisclasswillnotbeallowedtomanipulatetheseguysdirectly.Theyarenotfor'
public'
use.Thefunctionsunderthepublicstatementareforpublicuse.Thefirstthreearecalledconstructors.ThesefunctionsarecalledanytimeanewCLineclassiscreated.Herearesomeexampleswhenthearecalled:
//thiscallsCLine()
CLineMyLine;
//thisisapointertoaCLineclass
CLine*pMyLine;
//this
callsCLine()
pMyLine=newCLine;
//thiscallsCLine(intx1,inty1,intx2,inty2)
pMyLine=newCLine(0,0,10,10);
CLineMyLine(0,0,10,10);
Alloftheseconstructaline.Someinitializeittoitsdefaultsettingsandotherscopycoordinates.The'
new'
keywordisusedtocreatenewthingsinC++,likemallocinC.Youneedtocall'
delete'
foreverythingyousaynewto,likefreeinC.Thisgoesforclassesaswellasotherdatatypes.Icouldallocateanarrayof100integerswith:
//apointertosomeintegers
int*pNumbers;
//makememoryfor100ofthem
pNumbers=newint[100];
//setthefirstelementto0
pNumbers[0]=0;
//setthelastelementto99
pNumbers[99]=99;
//freethememory.
delete[]pNumbers;
Noticethe[]afterthedelete.Thisistotelltheprogramtodeletetheentirearray.Ifyousay'
deletepNumbers;
youwillonlyfreememoryforthefirstelement.Youwillthenbe'
leaking'
memory.Memoryleaksarewhenyouforgettodeletememory.Thismayendupcrashingyourcomputerifyouuseallthecomputersmemory.
Sorry,let'
sgetbacktotheconstructorsforCLine.Thecodefortheseconstructorfunctionswhichautomagicallygetcalledwhenanewlineiscreatedwilllooklike:
CLine:
:
CLine()
m_nX1=0;
m_nX2=0;
m_nY1=0;
m_nY2=0;
CLine(intx1,inty1,intx2,inty2)
m_nX1=x1;
m_nX2=x2;
m_nY1=y1;
m_nY2=y2;
Noticethatthefunctiondeclarationismuchlikearegular'
functionexceptthatweputtheclassnameandtwocolonsinfrontofthefunctionname(CLine:
).Onedifferencewithconstructorsisthattheydon'
thaveareturnvalue.Thisisthecasefordestructorsalso.AdestructoristhefunctionwhichautomagicallygetscalledwhenourCLineisdeletedorgoesoutofscope.Forinstance:
//memoryfortheclassisclearedupand~CLine()iscalled
deletepMyLine;
//this'
}'
endsthesectionoftheprogramwhereMyLineis
//valid.~CLine()willbecalled.(MyLinegoesoutof'
scope'
)
Forourclass,~CLine()doesn'
tneedtodoanything.However,sometimesyoumaywanttoputyourcleanupcodehere.Likedeletinganyallocatedmemoryinyourclass.Sincewehavenothingtodooutfunctioncodeisempty:
~CLine()
//donothing
sfillintheother2functions.
voidCLine:
SetPoints(intx1,inty1,intx2,inty2)
return;
Draw()
//psuedocodehere,theseareoperatingsystemfunctionstodrawaline
MoveTo(m_nX1,m_nY1);
LineTo(m_nX2,m_nY2);
HowwouldIcallthesefunctions?
Hereareacoupleofexamples.Onewithpointersandonewithout.
CLine*pLine=newCLine(0,0,10,10);
pLine->
Draw();
deletepLine;
MyLine.SetPoints(0,0,10,10);
MyLine.Draw();
That'
sitfortheclass.Nowthisclasscanbeusedinotherclasses.YoucanimagineaCSquareclassthathas4Clineclassesinit:
classCSquare
CLinem_LineTop;
CLinem_LineLeft;
CLinem_LineBottom;
CLinem_LineRight;
...
Orbetteryet,thepointofallofthisclassstuff,youcanusetheCLineclasstomakeyourownclass.ThisisdoneatoninVisualC.Letssayyouwantedtodrawlinesinyourprogram,andyouthoughtthelineclassmightbenice,butitismissinganimportantfeature,itdoesn'
tletyousetthelinecolor.Insteadofwritingawholenewclass,youcansimpleinherittheCLineclass.Thiswouldlooklikethis:
classCColorLine:
publicCLine
voidDraw(longcolor);
};
What'
sgoingonhere?
Wellwiththisclasswehaveallthefunctionalityofourotherclass,butnowwecanusethisotherDraw()functionwhichallowsustosetthecolor.TheCPPcodewouldlooklike:
voidCColorLine:
Draw(longcolor)
SetColor(color);
CLine: