Visual C++ 2008入门经典.docx_第1页
Visual C++ 2008入门经典.docx_第2页
Visual C++ 2008入门经典.docx_第3页
Visual C++ 2008入门经典.docx_第4页
Visual C++ 2008入门经典.docx_第5页
已阅读5页,还剩171页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Visual C+ 2008入门经典Chapter 1: Programming with Visual C+ 2008CLR console programsMFC-based Windows programWindows Forms programChapter 2: Data, Variables, and CalculationsLiteralsenumescape sequencesExplicit Castsbitwise operatorsVariable scopeC+/CLI Programming C+/CLI Specific Formatting the OutputThere are 25 packages weighing 7.50 pounds. “ddd.dd” C+/CLI Input from the KeyboardConsole:WriteLine(LRoom size is 0:F2 yards by 1:F2 yards,roomLengthYds, roomWidthYds);Suit suit = Suit:Clubs;int value = safe_cast(suit);Console:WriteLine(LSuit is 0 and the value is 1 , suit, value);Console:WriteLine(LPress any key.);Console:ReadKey();Chapter 3: Decisions and LoopsIfSwitchswitch(letter*(letter = a & letter = z) case a: case e: case i: case o: case u: cout endl You entered a vowel.; break;ForWhileDo whileC+/CLI ProgrammingFor eachString proverb = LA nod is as good as a wink to a blind horse.;for each(wchar_t ch in proverb)Get a key combinationConsole:WriteLine(LPress a key combination - press Escape to quit.); ConsoleKeyInfo keyPress; do keyPress = Console:ReadKey(true); Console:Write(LYou pressed); if(safe_cast(keyPress.Modifiers)0) Console:Write(L 0, keyPress.Modifiers); Console:WriteLine(L 0 which is the 1 character, keyPress.Key, keyPress.KeyChar); while(keyPress.Key != ConsoleKey:Escape);Chapter 4: Arrays, Strings, and PointersArraysCharacter Arrays and String Handling0Indirect Data Access=6Dynamic Memory AllocationThis extends to two or more dimensions but with the restriction that only the leftmost dimension may be specified by a variableUsing ReferencesA reference must be initialized in its declarationA reference cant be reassigned to another variableNative C+ Library Functions for StringsThe strcpy_s() function is a more secure version of strcpy(). The strspn() function searches a string for the first character that is not contained in a given set andreturns the index of the character found.C+/CLI ProgrammingTracking HandlesA tracking handle is a form of pointer used to reference variables defined on the CLR heap. A tracking handle is automatically updated if what it refers to is relocated in the heap by the garbage collectorCLR ArraysStringsTracking ReferencesInterior PointersAn interior pointer is a C+/CLI pointer type to which you can apply the same operation as a native pointer. array samples = gcnew array(50); / Generate random element values Random generator = gcnew Random; for(int i = 0 ; iLength ; i+) samplesi = 100.0*generator-NextDouble();for each(double sample in samples)Array:Sort( names,weights); / Sort the arrays for each(String name in names) / Output the names Console:Write(L0, 10, name); Console:WriteLine(); for each(String name1 in toBeFound) / Search to find weights result = Array:BinarySearch(names1, name1); / Search names arrayarray products = gcnew array(SIZE,SIZE);for (int i = 0 ; i SIZE ; i+)for(int j = 0 ; j SIZE ; j+)productsi,j = (i+1)*(j+1);array values = 2, 456, 23, -46, 34211, 456, 5609, 112098,234, -76504, 341, 6788, -909121, 99, 10;String formatStr1 = 0,; / 1st half of format stringString formatStr2 = ; / 2nd half of format stringString number; / Stores a number as a string/ Find the length of the maximum length value stringint maxLength = 0; / Holds the maximum length foundfor each(int value in values)number = + value; / Create string from valueif(maxLengthLength)maxLength = number-Length;/ Create the format string to be used for outputString format = formatStr1 + (maxLength+1) + formatStr2;array data = 1.5, 3.5, 6.7, 4.2, 2.1;interior_ptr pstart = &data0;interior_ptr pend = &datadata-Length - 1;double sum = 0.0;while(pstart = pend)sum += *pstart+;array array grades = gcnew array array gcnew arrayLouise, Jack, / Grade A gcnew arrayBill, Mary, Ben, Joan, / Grade Bgcnew arrayJill, Will, Phil, / Grade Cgcnew arrayNed, Fred, Ted, Jed, Ed, / Grade Dgcnew arrayDan, Ann / Grade E;wchar_t gradeLetter = A;for each(array grade in grades)while(index = sentence-IndexOfAny(punctuation, index) = 0)indicatorsindex = L; / Set marker+index; / Increment to next character+count; / Increase the countChapter 5: Introducing Structure into Your ProgramsPassing Arguments to a FunctionReturning Values from a FunctionRecursive Function CallsC+/CLI ProgrammingFunctions Accepting a Variable Number of ArgumentsArguments to main()Functions should be compact units of code with a well-defined purpose. A typical program willconsist of a large number of small functions, rather than a small number of large functions.Passing values to a function using a reference can avoid the copying implicit in the call-by-valuetransfer of arguments. Parameters that are not modified in a function should be specified as const.When returning a reference or a pointer from a native C+ function, ensure that the object beingreturned has the correct scope. Never return a pointer or a reference to an object that is local to anative C+ function.In a C+/CLI program there is no problem with returning a handle to memory that has beenallocated dynamically because the garbage collector takes care of deleting it when it is no longerrequired.Chapter 6: More about Program StructurePointers to Functions A Pointer to a Function as an Argument Arrays of Pointers to Functions ExceptionsHandling Memory Allocation Errors Function Overloading Function Templates An Example Using Functions C+/CLI Programming Understanding Generic Functions A Calculator Program for the CLR String eatspaces(String str); / Function to eliminate blanksdouble expr(String str); / Function evaluating an expressiondouble term(String str, int index); / Function analyzing a termdouble number(String str, int index); / Function to recognize a numberString extract(String str, int index); / Function to extract a substringChapter 7: Defining Your Own Data TypesThe struct in C+Data Types, Objects, Classes, and InstancesThe Pointer thisStatic Members of a ClassReferences to Class ObjectsC+/CLI ProgrammingDefining Value Class Types Defining Reference Class Types Defining a Copy Constructor for a Reference Class Type Class Properties initonly Fields Static Constructorsvalue class Heightref class Box / The height in meters property double meters / Scalar property / Returns the property value double get() return inchesToMeters*(feet*inchesPerFoot+inches); / You would define the set() function for the property here. Console:WriteLine(LShe is 0, her-Name); Console:WriteLine(LHer weight is 0:F2 kilograms., her-getWeight().kilograms); Console:WriteLine(LHer height is 0 which is 1:F2 meters., her-getHeight(),her-getHeight().meters);property String defaultintString get(int index)if(index = Names-Length)throw gcnew Exception(LIndex out of range); return Namesindex; / List the namesfor(int i = 0 ; i NameCount ; i+)Console:WriteLine(LName 0 is 1, i+1, myNamei);Chapter 8: More on ClassesImplementing a Copy Constructorclass CMessageprivate:char* pmessage; / Pointer to object text stringUnionsOperator OverloadingClass TemplatesAdding Function MembersOrganizing Your Program CodeC+/CLI ProgrammingOverloading Operators in Value Classes Overloading the Increment and Decrement Operators Overloading Operators in Reference Classes Implementing the Assignment Operator for Reference TypesChapter 9: Class Inheritance and Virtual FunctionsInheritance in Classes=myBox.ShowVolume(); / Display volume of base boxmyGlassBox.ShowVolume(); / Display volume of derived boxClass Members as FriendsVirtual FunctionsC+/CLI ProgrammingInheritance in C+/CLI Classes Interface Classes Defining Interface Classes Classes and Assemblies Functions Specified as new Delegates and Events Destructors and Finalizers in Reference Classes Generic Classes Handler handler = gcnew Handler(HandlerClass:Fun1); / Delegate object Console:WriteLine(LDelegate with one pointer to a static function:); handler-Invoke(90); handler += gcnew Handler(HandlerClass:Fun2); Console:WriteLine(LnDelegate with two pointers to static functions:); handler-Invoke(80);To create a class library you can first create a CLR project with the name Ex9_16lib using the ClassLibrary template.#using public delegate void DoorHandler(String str);/ Add handler for Knock event member of door door-Knock += gcnew DoorHandler(answer, &AnswerDoor:ImIn); door-TriggerEvents(); / Trigger Knock events/ Change the way a knock is dealt with door-Knock -= gcnew DoorHandler(answer, &AnswerDoor:ImIn); door-Knock += gcnew DoorHandler(answer, &AnswerDoor:ImOut); door-TriggerEvents(); / Trigger Knock eventsusing namespace System:Collections:Generic; / For generic collectionsList numbers = gcnew List;LinkedList values = gcnew LinkedList; A function in a base class may be declared as virtual. This allows other definitions of thefunction appearing in derived classes to be selected at execution time, depending on the typeof object for which the function call is made.Chapter 10: The Standard Template LibraryContainersContainer AdaptersIteratorsAssociative ContainersThe STL for C+/CLI ProgramsSTL/CLR Containers Using Sequence Containers Using Associative Containerslist data = gcnew list(); for(int i = 0 ; ipush_back(valuesi);/ Storing phone numbers in a mapmap phonebook = gcnew map();first = Console:ReadLine(); for(iter = book-begin() ; iter != book-end() ; iter+) Console:WriteLine(L0, -301,-12, iter-first, iter-second);Chapter 11: Debugging TechniquesCommon BugsBasic Debugging OperationsAuto :显示当前语句与上一条语句的自动变量Advanced BreakpointsDebug/windows/breakpoints可以设置条件(右键)Setting Tracepoints右键代码行:breakpoint|when hit可以在output上打印信息,可以选择多个宏退出程序,输出(output)显示:main(array ),The Value no is 1Changing the Value of a Variable需要return程序循环次数修改,可以执行最后几步Adding Debugging CodeUsing AssertionsAdding Your Own Debugging CodeDebugging a ProgramThe Call Stack显示尚未完成的函数调用序列双击可以显示发生问题时,程序正在执行的行利用Auto可以显示变量内容,从而发现问题Step Over to the ErrorFinding the Next Bugselect the Break button the Call Stack window tells you what is wrongDebugging Dynamic Memory/ Ex11_02.cpp : Extending the test operationCrtSetDbgFlag( _CRTDBG_LEAK_CHECK_DF|_CRTDBG_ALLOC_MEM_DF ); / Direct warnings to stdout _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);在CLR下 不需要,自动提示内存泄漏,加以上代码反倒不显示!Debugging C+/CLI Programs在CLR下 ,自动提示内存泄漏,指针破坏。/ Ex11_03.cpp : main project file./ CLR trace and debug output#using using namespace System;using namespace System:Diagnostics;void FunC() Trace:Indent(); Trace:WriteLine(LStarting FunC); if(sw-TraceError) Debug:WriteLine(LFunC error.); Debug:Assert(value Draw(&aDC); delete m_pTempElement; / Delete the old element m_pTempElement = 0; / Reset the pointer to 0 / Create a temporary element of the type and color that / is recorded in the document object, and draw it m_pTempElement = CreateElement();/ Create a new element m_pTempElement-Draw(&aDC); / Draw the element Drawing with the CLRprivate: System:Void Form1_MouseDown(System:Object sender, System:Windows:Forms:MouseEventArgs e) if(e-Button = System:Windows:Forms:MouseButtons:Left) drawing = true; firstPoint = e-Location; private: System:Void Form1_MouseMove(System:Object sender, System:Windows:Forms:MouseEventArgs e) if(drawing) switch(elementType) case ElementType:LINE: tempElement = gcnew Line(color, firstPoint, e-Location); break; case ElementType:RECTANGLE: tempElement = gcnew Rectangle(color, firstPoint, e-Location); break; case ElementType:CIRCLE: tempElement = gcnew Circle(color, firstPoint, e-Location); break;private: System:Void Form1_Paint(System:Object sender, System:Windows:Forms:PaintEventArgs e) Graphics g = e-Graphics; if(tempElement) tempElement-Draw(g); Chapter 16: Creating the Document and Improving the ViewThe MFC Collection ClassesThe CArray Template ClassThe first argument is the type of the object to be stored The second argument is the type used in member function callsPointArray.Add(aPoint);aPoint = PointArray.GetAt(2);aPoint = PointArray2; / Store a copy of the third elementPointArray.SetAt(3,NewPoint); / Store NewObject in the 4th elementPointArray3 = NewPoint; / Same as previous line of codeThe CList Template ClassPointList.AddTail(aPoint); / Add an element to the endPointList.InsertBefore(aPosition, ThePoint);PointList.SetAt(aPosition, aPoint);POSITION aPosition = PointList.Find(ThePoint);PointList.RemoveAll();The CMap Template ClassHashValue = Key%101;The Typed Pointer CollectionsUsing the CList Template Classclass CCurve: public CElement/ Rest of the class tected:CCurve(void); / Default constructor - should not be usedCList m_P

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论