第二部分 托管类程序设计

Click here to load reader

Upload: candice-mack

Post on 03-Jan-2016

90 views

Category:

Documents


4 download

DESCRIPTION

第二部分 托管类程序设计. 第十四章 托管类 C++ 程序设计基础. 所谓托管类 C++ 程序是通过 Visual C++ 的 C++/CLI 扩展使用 .NET 框架提供的框架库 FCL 和其他功能设计和编写,并由公共 语言运行时 CLR 进行运行管理的 C++ 程序。 托管类 C++ 程序与非托管类 C++ 程序在形式上十分相似,程 序的书写语法上也基本一致,但由于程序中对 FCL 和 CLR 的使 用是通过 C++/CLI 扩展实现的,这是非托管类 C++ 程序没有的。 - PowerPoint PPT Presentation

TRANSCRIPT

  • C++

  • C++ Visual C++ C++/CLI .NET FCL CLR C++ C++ C++ FCL CLR C++/CLI C++ C++ C++ C++ C++ C++/CLI

  • 14.11 #includeC++ .h.h.cpp #include #include stdafx.h C++/CLI .h.cpp #include stdafx.h 2 #usingC++

  • C++/CLI .dll#using 3 using namespace C++ C++/CLI C++ using namespace std;C++/CLI using namespace System;C++/CLI FCL System

  • System CodeDom, Collections, ComponentModel, Configuration, Data, Deployment, Diagnostics, DirectoryServices, Drawing, EnterpriseServices, Globalization, IdentityModel, Internal, IO, Linq, Management, Media, Messaging, Net, Printing, Reflection, Resource, Runtime, Security, ServiceModel, ServiceProcess, Speech, Text, Threading, Timers, Transaction, Transactions, Web, Windows, Workflow XmlSystem::CodeDom compiler

  • System::Collections Generic, IList, ObjectModel SpecializedSystem::ComponentModel Design, IBindingList IEditableObjectSystem::Configuration Assemblies, Install, Internal ProviderSystem::Data Common, Design, Linq, Odbc, OleDb, OracelClient, Sql, SqlClient SqlTypesSystem::Deployment Application Internal

  • System::Diagnostics CodeAnalysis, Design, Eventing, PerformanceData SymbolStoreSystem::DirectoryServices AccountManagement, ActiveDirectory ProtocolsSystem::Drawing Design, Drawing2D, Imaging, Printing TextSystem::EnterpriseServices CompensatingResourceManagerSystem::IdentiyModel Claims, Policy, Selectors Tokens

  • System::IO Compression, IsolatedStorage, Log, Packaging, Pipes PortsSystem::Linq ExpressionsSystem::Management InstrumentationSystem::Messaging DesignSystem::Net Cache, Configuration, Mail, Mime, NegotiateStream, NetworkInformation, PeerToPeer, Collaboration, Security, Sockets SslStream

  • System::Printing IndexedProperties InteropSystem::Reflection EmitSystem::Resources Tools System::Runtime CompilerServices, ConstrainedExecution, Hosting, InteropServices, Remoting, Serialization VersioningSystem::Security AccessControl, Authentication, Cryptography, Permissions, Policy,Principal RightsManagement

  • System::ServiceModel Activation, Channels, ComIntegration, Configuration, Description, Diagnostics, Dispatcher, Internal, MsmqIntegration, PeerResolvers, Persistence, Security, Syndication WebSystem::ServiceProcess Design System::Speech AudioFormat, Recognition SynthesisSystem::Text RegularExceptions

  • System::Trasactions ConfigurationSystem::Web Caching, ClientServices, Compilation, Configuration, Handlers, Hosting, Mail, Management, Mobile, Profile, Query, RegularExpressions, Script, Security, Services, SessionState, UI UtilSystem::Windows Annotation, Automation, Controls, Converters, Data, Documents, Forms, Ink, Input, Interop, Markup, Media, Navigation, Resources, Shapes, Threading Xps

  • System::Workflow Activities, ComponentModel Runtime System::Xml Linq, Schema, Serialization, XPath XslSystem::ComponentModel::Design DataSystem::Data::Linq Mapping SqlClientSystem::Diagnostics::Eventing Reader

  • System::Runtime::InteropServerces ComTypes, CustomMarshalers ExpandoSystem::Runtime::Remoting Activation, Channels, Contexts, Lifetime, Messaging, Metadata, MetadataServices, Proxies ServicesSystem::Runtime::Serialization Configuration, Formatters JsonSystem::Security::Cryptography Pkcs, X509Certificates XmlSystem::ServiceModel::Activation Configuration

  • System::ServiceModel::Security TokensSystem::Speech::Recognition SrgsGrammarSystem::Speech::Synthesis TtsEngineSystem::Web::ClientServices ProvidersSystem::Web::Configuration InternalSystem::Web::Query Dynamic

  • System::Web::Script Serialization ServicesSystem::Web::Services Configuration, Description, Discovery ProtocolsSystem::Web::UI Adapters, Design, HtmlControls, MobileControls WebControlsSystem::Windows::Annotation StorageSystem::Windows::Automation Peers, Providers Text

  • System::Windows::Controls PrimitivesSystem::Windows::Documents DocumentStructures SerializationSystem::Windows::Forms ComponentModel, Design, Integration, Layout, PropertyGridInternal VisualStylesSystem::Windows::Ink AnalysisCoreSystem::Windows::Markup Localizer Primitives

  • System::Windows::Media Animation, Converters, Effects, Imaging, Media3D TextFormttingSystem::Windows::Xps Packaging SerializationSystem::Workflow::ComponentModel Compiler DesignSystem::Workflow::Runtime Configuration, DebugEngine, Hosting TrackingSystem::Xml::Serialization Advanced Configuration

  • System::Xml::Xsl RuntimeSystem::Runtime::Remoting::Channels Http, Ipc TcpSystem::Runtime::Remoting::Metadata W3cXsd2001System::Workflow::Activities::Rules DesignSystem::Runtime::Serialization::Formatters Binary Saop

  • System::Web::UI::Design WebControlsSystem::Web::UI::MobileControls AdaptersSystem::Web::UI::WebControls Adapters WebPartsSystem::Windows::Forms::ComponentModel Com2InteropSystem::Windows::Forms::Design BehaviorSystem::Windows::Media::Media3D Converters

  • WebControls System::Web::UI::Design::WebControls WebParts

  • 4#pragma once Visual Studio.NET C++ C++/CLI

  • 14.2 C++ I/O MFC CDC GDI C++/CLI System Console ReadReadKey ReadLine Write WriteLine

  • String ^number;Console::WriteLine( LWelcom to Visual C++ .NET Programming! );Console::Write( LPlease Enter a Number: );number = Console::ReadLine(); C++/CLI System::Drawing Graphics GDI+

  • 14.3C++ C++ * new * delete

  • C++/CLI value typeref type FCL .NET ^^ hat gcnew ^ ^

  • C++ * new ^ gcnew ^ ^ gcnew

  • Stirng ^firstPrompt = gcnew String( LPlease the first integer: );Stirng ^secondPrompt = gcnew String( LPlease the second integer: );String ^firstNumber, ^secondNumber;Console::WriteLine( firstPrompt );firstNumber = Console::ReadLine();Console::WriteLine( secondPrompt );secondNumber = Console::ReadLine();

  • 1 * new * delete * delete 2 ^ gcnew ^

  • C++/CLI delete gcnew C++ delete[] delete ^ C++/CLI delete

  • delete

  • C++/CLI delete

  • 3 ^ ^ Stirng ^firstPrompt = nullptr;// nullptr Stirng ^firstPrompt = null;// MC++ Stirng ^firstPrompt = 0; // MC++ C++ delete nullptr

  • 4 MC++ ^ * new String *string = String( LWelcome to Visual C++ .NET Programming! );5 ^

  • 14.4 C++ ASCII 8 char ASCII x$7*\n std string

  • char str[] = Welcome to Visual C++ .NET Programming!; C++/CLI char Unicode char Unicode Unicode 16 __wchar_t wchar_t Unicode x$7*\n

  • System::Array System String C++ string L wchar_t str[] = LWelcome to Visual C++ .NET Programming!; C++ __wchar_t wchar_t Unicode

  • 14.5FCL FCL struct .NET C++ C++/CLI C++ C++/CLI FCL Int32 int

  • #include stdafx.h#using using namespace System;int main(){String ^firstNumber, ^secondNumber;int number1, number2, sum;

    Console::Write( LPlease Enter the first integer: );firstNumber = Console::ReadLine();

    Console::Write( LPlease Enter the second integer: );secondNumber = Console::ReadLine();

  • number1 = Int32::Parse( firstNumber );number2 = Int32::Parse( secondNumber );sum = number1 + number2;

    Console::WriteLine( L\nThe sum is {0}., sum.ToString() );

    return 0;} int Int32 Parse ToString Int32

  • FCL C++/CLI C++/CLI BooleanboolBytechar8 SBytesigned char8 Char__wchar_t16 Unicode Int16short16 UInt16unsigned short16 Int32int long32 UInt32unsigned int / long32

  • C++/CLI Int64__int6464 UInt64unsigned __int6464 Singlefloat32 Doubledouble64 DecimalDecimal96 ObjectObject^StringString^ Unicode

  • 14.6 C++/CLI C++ math.h FCL C++ FCL Math Math System E PI e Abs Exp SinCosTan

  • SinhCoshTanh AsinAcosAtanAtan2 LogLog10 Pow Sqrt Max Min Round Floor Math :: Math::PI Math::Sqrt( 25.0 )

  • FCL ByteUInt16, Int16, UInt32, Int32, Uint64, Int64, Single, Double DecimalSByteInt16, Int32, Int64, Single, Double DecimalInt16Int32, Int64, Single, Double DecimalUInt16UInt32, Int32, UInt64, Int64, Single, Double Decimal

  • CharUInt16, UInt32, Int32, UInt64, Int64, Single, Double DecimalInt32Int64, Single, Double DecimalUInt32Int64, Single, Double DecimalInt64DecimalUInt64DecimalSingleDouble System Convert Int32 Int64

  • int number;__int64 longNumber = Convert::ToInt64( number );

  • 14.7 C++/CLI Managed Array System::Array C++/CLI 1[qualifiers] [cli::]array ^var;qualifiersmutable, volatile, const, extern statcarray cli using namespace cli; array cli::

  • type ^ *dimension 1 32vararray ^intArray;// array ^strArray1;// String^ array ^strArray2;// String^ array ^doubleArray;// double

  • var = gcnew [cli::]array(val [, val]);gcnewvalintArray = gcnew array(100);strArray1 = gcnew array(50);strArray2 = gcnew array(5, 10);doubleArray = gcnew array(10, 10);

  • array ^intArray = gcnew array(100);array ^strArray2 = gcnew array(5,10); System::Array CreateInstance array ^intArray = Array::CreateInstance( int, 100 );array ^strArray2 = Array::CreateInstance( String^, 5, 10 );

  • 2array ^intArray = gcnew array{ 20, 15, 30, 25, 12, 10, 8, 45, 9, 22 };

    array strArray =gcnew array{ { LJohn, Lmale, LNew York},{ LMerry, Lfemale, LWashington},{ LSmith, Lmale, LHouston} };

  • 3 System::Array GetValue SetValue int value = intArray[5];intArray[5] = 20;String ^str = strArray[2, 0];strArray[2, 0] = LHenrry;int value = intArray->GetValue( 5 );intArray->SetValue( 20, 5 );String ^str = strArray->GetValue( 2, 0 );strArray->SetValue( LHenrry, 2, 0 );

  • 4 System::Array Sort BinarySearch System::Array Sort

  • intArray Array::Sort( intArray ); intArray 1 5 Array::Sort( intArray, 1, 5 ); System::Array BinarySearch intArray int pos = Array::BinarySearch ( intArray, (Object^)25 );

  • intArray 1 5 int pos = Array::BinarySearch ( intArray, 1, 5, (Object^)25 ); -15 MC++ int a __gc[];a = new int __gc[10];int b __gc[] = { 20, 15, 30, 25, 12, 10, 8, 45, 9, 22 };String *str1[,] = new String*[4, 2];String *str2[,] = { { LJohn, Lmale, LNew York},{ LMerry, Lfemale, LWashington} };

  • 14.8 C++/CLI C++ C++ 1class_access ref class name modifier: inherit_access base_type { }; // class_access ref struct name modifier: inherit_access base_type { }; //

  • class_access value class name modifier: inherit_access base_type { }; // class_access value struct name modifier:inherit_access base_type { }; // class_access public private privateC++ ref classvalue classref struct value structC++ class struct

  • name C++ modifier abstract sealedC++ inherit_access public public C++ publicprotected private private

  • base_type 0 interface 0 1 0 interfaceC++ 0 C++ public ref class MyRefClass { };public ref struct MyRefStruct { };public value class MyValClass { };public value struct MyValStruct { };

  • ref class/ref struct value class/value struct sealed

  • X Y Pixel C++/CLI enum class C++ enum Status { CONTINUE, NOW, LOST };

  • C++/CLI enum class Status { CONTINUE, WON, LOST };C++ int gameStatus = WON; C++/CLI int gameStatus = Status::WON;

  • MC++ __gc class __gc struct __value class __value struct public __gc class MyRefClass { };public __gc struct MyRefStruct { };public __value class MyValClass { };public __value struct MyValStruct { };

  • System Object System ValueType ValueType Object Object Object ^ Object Object

  • int i = 5;// create an int value on the stack// explicitly box the int valueObject ^object1 = static_cast< Object^ >( i );// imexplicitly box the int valueObject ^object2 = i;Object int x = static_cast< int >( object1 );Object Object InvalidCastException

  • int i = 5; // create an int value on the stackint ^intObject = i;// imexplicitly box the int value in an int objectint x = *intObject;// imexplicitly unbox the int object Object int intObject value class ValueType

  • MC++ __box int i __box( i );

  • 2 ^* ^C++ * C++ privatepublic protected

  • private public C++ static privatepublic protected

  • 3 private C++ protected public C++ static C++

  • C++ 4 C++/CLI C++ C++/CLI const C++/CLI const C++/CLI const const const

  • CLI .NET C# C++ const C++/CLI const const C++/CLI const const const C++/CLI const

  • C++/CLI const C++/CLI C++ static const literal literal ref class X{literal int i = 4;}; literal

  • C++/CLI initonly initonly ref class Y{initonly static int staticConst1;initonly static int staticConst2 = 0;static Y() { staticConst1 = 0; staticConst2 = 1;

  • }}; literal initonly C++/CLI friend

  • 4 property public property property type name property type name{type get(){ }

  • void set( type value ){ }} Timer private hour Hour public ref class Timer{public:

  • property int Hour{int get() { return hour; }void set( int value ) { hour = value; }}private:int hour;};

  • public Timer ^ Hour Timer ^timer = gcnew Timer();int hour = timer->Hour;// int hour = timer->Hour::get();timer->Hour = (hour + 12) % 24; // timer->Hour::set((hour+12)%24); Box private dimensions Dimensions

  • public ref class Box{public:property double Dimensions{double get( int index ){ return( index < 0 || index > dimensions->Length ) ?-1 : dimensions[ index ];}void set( int index, double value ) { if( index >= 0 || index < dimensions->Length )dimension[ index ] = value;}}

  • private:static array ^dimensions = gcnew array( 3 ); }; Box ^ Dimensions Box ^box = genew Box();for( int i = 0.0; i < 3; i++ )box->Dimensions[ i ] = 2.0 * ( i + 1.0 );// box->Dimensions::set(i, 2.0*(i+1.0));// or box->Dimensions->default::set(i, 2.0*(i+1.0));

  • double volume = 0.0; for(int i = 0; i < 3; i++)volume = 1.0 * box->Dimensions[i];// height = box->Dimensions::get(i);// or height = box->Dimension->default::get(i); get

  • 5 ^ * ^ * cli interior_ptr

  • interior_ptr ^ interior_ptr [cli::]interior_ptr var [= &initializer] ;cv_qualifier const volatiletype var initializer varinterior_ptr ^ interior_ptr ref class MyClass {public:int data;};

  • int main(){MyClass ^myclass = gcnew MyClass();myclass->data = 1;Console::WriteLine( myclass->data.ToString() );

    interior_ptr p = &( myclass->data );*p = 2;Console::WriteLine( myclass->data.ToString() );

    interior_ptr p1 = &myclass;(*p1)->data = 3;Console::WriteLine( (*p1)->data.ToString() );}

  • 6 interior_ptr *void native_function( int *p ){for( int i = 0; i < 10; i++ ) p[i] = i; }array ^arr = gcnew array(10);interior_ptr p = &arr[0];int *np = p;// native_function( np );

  • cli pin_ptr * interior_ptr pin_ptr pin_ptr *array ^arr = gcnew array(10);pin_ptr p = &arr[0];int *np = p;native_function(np);

  • 14.9 C++ X class X{public:virtual void fun() = 0;};

  • C++/CLI C++ abstract C++ abstract X

  • ref class X abstract{public:virtual void fun1() = 0;virtual void fun2() abstract;virtual property IsConnected{bool get() abstract;}};

  • C++/CLI X fun1fun2 IsConnected Xinterface class X{public:void fun1();void fun2();property bool IsConnected { bool get(); }};

  • property bool IsConnected { bool get(); } IsConnected IsConnected property bool IsConnected; virtual X Y ref class Y : public X{public:

  • virtual void fun1(){}virtual void fun2(){}property bool IsConnected{virtual bool get(){return connected;}}private: bool connected;};

  • C++ C++/CLI C++ virtual C++/CLI virtual override new Shape Circle Circle Shape draw

  • ref class Shape{public: virtual void draw() abstract;};ref class Circle : public Shape{public: virtual void draw() override;};void Circle::draw() { }

  • ref class Circle : public Shape{public: virtual void draw() override { }};ref class Circle : public Shape{public: virtual void draw() new;};

  • void Circle::draw() { }ref class Circle : public Shape{public: virtual void draw() new { }};

  • C++/CLI Circle display draw ref class Circle : public Shape{public: virtual void display() = Shape::draw;};

  • Shape ^s = gcnew Circle;s->draw(); Circle display C++/CLI sealed Shape draw void draw() sealed; Shape draw sealed

  • sealed sealed

  • 14.10

  • C++/CLI C++/CLI Delegates DelegateTest delegate

  • DelegateBubbleSortpublic ref class DelegateBubbleSort{public:delegate bool Comparator( int, int );// sort array using Comparator delegatestatic void SortArray( array^, Comparator^ );private:// swap two elementsstatic void Swap( interior_ptr, interior_ptr );};// end class delegateBubbleSort

  • #include "DelegateBubbleSort.h"// sort array using Comparator delegatevoid DelegateBubbleSort::SortArray( array ^arr, Comparator ^Compare ){for( int pass = 0; pass < arr->Length; pass++ )for( int i = 0; i < arr->Length - 1; i++ )if( Compare( arr[i], arr[i+1] ) )Swap( &arr[i], &arr[i+1] );}// end method SortArray

  • // swap two elementsvoid DelegateBubbleSort::Swap( interior_ptr firstElement, interior_ptr secondElement ){int hold = *firstElement;*firstElement = *secondElement;*secondElement = hold;}// end method Swap

  • BubbleSort #include "DelegateBubbleSort.h"public ref class BubbleSort{public:BubbleSort();// constructorvoid PopulateArray();// sort the arrayvoid SortArrayAscending();void SortArrayDescending();virtual String ^ToString() override;

  • private:static array ^elementArray = gcnew array(10);// delegate implementation for ascending sortbool SortAscending( int, int );// delegate implementation for descending sortbool SortDescending( int, int );};// end class BubbleSort BubbleSort #include "BubbleSort.h"BubbleSort::BubbleSort(){PopulateArray();}// end constructor

  • // delegate implementation for ascending sortbool BubbleSort::SortAscending( int element1, int element2 ){return element1 > element2 ;}// end method SortAscending// delegate implementation for descending sortbool BubbleSort::SortDescending( int element1, int element2 ){return element1 < element2 ;}// end method SortDescending

  • // populate the array with random numbersvoid BubbleSort::PopulateArray(){// create random-number generatorRandom ^randomNumber = gcnew Random();// populate elementArray with random integersfor( int i = 0; i < elementArray->Length; i++ )elementArray[i] = randomNumber->Next( 100 );}// end method PopulateArray

  • // sort randomly generated numbers in ascending ordervoid BubbleSort::SortArrayAscending(){DelegateBubbleSort::SortArray( elementArray, gcnew DelegateBubbleSort::Comparator( this, &BubbleSort::SortAscending ) );}// end method SortArrayAscending

  • // sort randomly generated numbers in descending ordervoid BubbleSort::SortArrayDescending(){DelegateBubbleSort::SortArray( elementArray, gcnew DelegateBubbleSort::Comparator( this, &BubbleSort::SortDescending ) );}// end method SortArrayDescending

  • // return the contents of the arrayString ^BubbleSort::ToString(){String ^contents;for( int i = 0; i < elementArray->Length; i++ ){contents = String::Concat( contents, elementArray[i].ToString(), L" " );}// end forreturn contents;}// end method ToString

  • int main( array ^args ){BubbleSort ^sortPtr = gcnew BubbleSort();String ^output = String::Concat( L"Unsorted array:\n", sortPtr->ToString() );sortPtr->SortArrayAscending();output = String::Concat( output, L"\n\nSorted ascending:\n", sortPtr->ToString() );sortPtr->SortArrayDescending();output = String::Concat( output, L"\n\nSorted descending:\n", sortPtr->ToString() );MessageBox::Show( output, L"Demonstrating delegates" );return 0;}// end main

  • 14.11 C++/CLI C++/CLI C++ template< typename >ref class ManagedStack{};

  • 14.12 C++/CLI .NET C++/CLI C++ CRL generic template % & const1 Stack Stack

  • #ifndef STACK_H#define STACK_Htemplate< typename T >ref class Stack{public:Stack( int = 10 );// default constructor (Stack size 10)// destructor~Stack(){delete[] elements;} // end ~Stack destructorbool push( const T& );// push an element onto the Stackbool pop( T& );// pop an element off the Stack// determine whether Stack is emptybool isEmpty()const

  • {return top == -1;} // end function isEmpty// determine whether Stack is fullbool isFull() const{return top == size 1;} // end function isFullprivate:int size;// # of elements in the Stackint top;// location of the top element (-1 means empty)array< T > ^elements;// internal representation of the Stack};// template constructortemplate< typename T >

  • Stack< T >::Stack( int s ) : size( s > 0 ? s : 10 ),// validate size top( -1 ),// Stack initially empty elements( gcnew array< T >( size )) // allocate memory for elements{} // end template Stack constructor// push element onto Stack// if successful, return true; otherwise, return falsetemplate< typename T >bool Stack< T >::push( T &pushValue ){if( !isFull() ){ elements[ ++top ] = pushValue;// place item on Stack return true; // pop successful} // end if

  • return false;// push unsuccessful} // end template function push// pop element off Stack// if successful, return true; otherwise, return falsetemplate< typename T >bool Stack< T >::pop( T &popValue ){if( !isEmpty() ){ popValue = elements[ top-- ];// remove item from Stack return true;// pop successful} // end ifreturn false;// pop unsuccessful} // end template function pop

  • #ifndef STACK_H#define STACK_H#include stdafx.h

    generic< typename T >ref class Stack{public:Stack( int stackSize );// constructor// destructor~Stack(){delete[] elements;} // end ~Stack destructorbool push( T% );// push an element onto the Stackbool pop( T% );// pop an element off the Stack

  • // determine whether Stack is emptybool isEmpty(){return top == -1;} // end function isEmpty// determine whether Stack is fullbool isFull(){return top == size 1;} // end function isFullprivate:int size;// # of elements in the Stackint top;// location of the top element (-1 means empty)array< T > ^elements;// internal representation of the Stack};

  • #include stdafx.h#include Stack.h

    // generic constructorgeneric< typename T >Stack< T >::Stack( int s ) : size( s > 0 ? s : 10 ),// validate size top( -1 ),// Stack initially empty elements( gcnew array< T >( size )) // allocate memory for elements{} // end generic Stack constructor

  • // push element onto Stack// if successful, return true; otherwise, return falsegeneric< typename T >bool Stack< T >::push( T %pushValue ){if( !isFull() ){ elements[ ++top ] = pushValue;// place item on Stack return true; // pop successful} // end ifreturn false;// push unsuccessful} // end generic function push

  • // pop element off Stack// if successful, return true; otherwise, return falsegeneric< typename T >bool Stack< T >::pop( T %popValue ){if( !isEmpty() ){ popValue = elements[ top-- ];// remove item from Stack return true;// pop successful} // end ifreturn false;// pop unsuccessful} // end generic function pop

  • Stack.h Stack.h Stack.cpp

  • #include stdafx.h#include Stack.husing namespace System// generic function to manipulate Stack< T >generic< typename T >void testStack( Stack< T > ^theStack, array< T > ^values, String ^stackName ){Console::WriteLine( Pushing elements onto {0}, stackName );// push elements onto Stackfor each( T value in values ){ if( theStack->push( value )) Console::Write( {0} , value );

  • else { Console::writeLine( \nStack is full. Cannot push {0}, value ); break; } // end else} // end for eachConsole::WriteLine( \nPoping elements from {0}, stackName );T popedValue // holds the value poped from the Stack// pop elements from Stackwhile( theStack->pop( popedValue )) Console::Write( {0} , popedValue );Console::WriteLine( \nStack is empty. Cannot pop );} // end function testStack

  • int main( array< System::String^ > ^args ){array< double > ^doubleValues = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };array< int > ^intValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };Stack< double > ^doubleStack = genew Stack< double >( 5 );Stack< int > ^intStack = gcnew Stack< int >( 10 );testStack( doubleStack, doubleValues, doubleStack );testStack( intStack, intValues, intStack );return 0;} // end main Stack

  • Pushing elements onto doubleStack1.1 2.2 3.3 4.4 5.5Stack is full. Cannot push 6.6

    Poping elements from doubleStack5.5 4.4 3.3 2.2 1.1Stack is empty. Cannot pop

    Pushing elements onto intStack1 2 3 4 5 6 7 8 9 10Stack is full. Cannot push 11

    Poping elements from intStack10 9 8 7 6 5 4 3 2 1Stack is empty. Cannot pop

  • 2

  • maximum > IComparable< T > System FCL double Double int Int32 IComparable< T > IComparable< T > CompareTo double double1, double2;double1.CompareTo( double2 );

  • IComparable< T > maximum #include stdafx.husing namespace System;// generic function determines the largest of there IComparable objectsgeneric< typename T > where T : IComparable< T >T maximum( T x, T y, T z ){T max = x;// assume x is initially the largest// compare y with maxif( y->CompareTo( max ) > 0 ) max = y;// compare z with max

  • if( z->CompareTo( max ) > 0 ) max = z;return max;} // end function maximumint main( array< System::String^ > ^args ){Console::WriteLine( Maximum of {0}, {1} and {2} is {3}\n, 3, 4, 5, maximum( 3, 4, 5 ));Console::WriteLine( Maximum of {0}, {1} and {2} is {3}\n, 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));Console::WriteLine( Maximum of {0}, {1} and {2} is {3}\n, pear, apple, orange, maximum( pear, apple, orange ));return 0;} // end main

  • Maximum of 3, 4 and 5 is 5Maximum of 6.6, 8.8 and 7.7 is 8.8Maximum of pear, apple and orange is pear3

  • .NET

  • C++/CLI