- •1.3.1 Введение 13
- •1.5.1 Введение 37
- •2. Introduction to Variables 69
- •3. Data Types 72
- •4. Techniques of Using Variables 90
- •5. Introduction to Classes 115
- •5.4.1 Introduction 129
- •6. Classes and Memory Management 131
- •6.1.1 Native References 131
- •6.5.1 Introduction 140
- •7. Classes Combinations and Inheritance 152
- •7.2.1 Introduction 165
- •7.3.1 Introduction 171
- •8. Data Input/Output, Reading, and Formatting 173
- •8.1.1 Introduction 173
- •8.5.1 Introduction 189
- •8.6.1 Introduction 195
- •9. Introduction to Functions 201
- •10. Details on Passing Arguments 225
- •10.3.1 Introduction 237
- •11. Classes and Functions 242
- •11.1.2 Practical Learning: Introducing Data Reading 243
- •11.5.1 Introduction 264
- •12. Classes and their Methods 268
- •12.1.2 Practical Learning: Introducing Data Reading 268
- •12.4.1 Introduction 284
- •13. Class Construction and Destruction 290
- •13.3.1 Introduction 311
- •14. The Properties of a Class 315
- •14.1.1 Introduction 315
- •15. Function Pointers and Delegates 337
- •15.1.1 Introduction 337
- •15.3.1 Introduction 346
- •16. Introduction to Conditions 359
- •16.1.1 Introduction 359
- •16.2.1 Introduction 369
- •25.3.1 Introduction 543
- •26. Multi-Dimensional Arrays 556
- •26.1.1 Introduction 556
- •26.2.1 Introduction 566
- •27.1.1 Introduction 595
- •34. Введение в коллекции 743
- •35. Основы коллекций платформы .Net (Fundamentals of .Net Support For Collections) 779
- •36. Встроенные интерфейсы коллекций 797
- •37. Встроенные классы коллекций 841
- •1.1Основы
- •1.1.1Введение в с
- •1.1.2Библиотека Win32
- •1.1.4Библиотека mfc
- •1.1.6Microsoft Visual Basic
- •1.2The Microsoft .Net Framework
- •1.2.1 Введение
- •1.2.2 Помощь сом
- •1.3.1Введение
- •1.3.2Компилятор
- •1.3.3Компилятор cl
- •1.4.1Функция main()
- •Int main()
- •1.4.2Консольный ввод и вывод
- •Void main()
- •Int X; // Целочисленная переменная X
- •1.4.3Директива препроцессора #pragma region
- •1.4.4Использование дескрипторов
- •Void Handles()
- •1.4.5Одномерные массивы
- •Void SingleDimensional()
- •1.4.6Многомерные массивы
- •Void CreateArr2()
- •Void CreateJaggedArray()
- •1.4.7Передача массивов функциями
- •1.4.8Классы значения
- •1.4.9Классы ссылки
- •1.4.10Интерфейсы
- •1.4.11Абстрактные классы
- •Void Foo2(){} // и так тоже можно
- •Virtual int Foo()override {return 1024;}
- •Void Abstract()
- •1.4.12Запечатанные классы и виртуальные функции
- •Void Sealed()
- •1.4.13 Видимость компонентов классов и структур
- •1.4.14Свойства
- •Void SimpleIndexProp()
- •Value class p4
- •Int Value;
- •Void set(int X, int value)
- •Void DifficultIndexedProperty()
- •Int Value;
- •Void set(int X, int value)
- •Void DefaultIndexedProperty()
- •1.4.15Деструкторы классов
- •Value class DestructorValue
- •Void SimpleDestructorDemo()
- •Void DerivedClassDestructorDemo()
- •Void Destructors()
- •1.4.16 Приведение типов
- •Void DynamicCast()
- •If(icomp)
- •Void SafeCast()
- •Void ExplicitTypeConversion()
- •Void Casting()
- •1.4.17 Класс Array
- •IStructuralComparable, iStructuralEquatable
- •Void DemoArray()
- •1.4.18 Введение в коллекции
- •Void DemoArrayList()
- •1.5.1Введение
- •Include file.H
- •1.5.3Создание консольного приложения
- •1.5.4Открытие проекта
- •1.5.7Start Without Debugging
- •1.5.8Code Comments
- •Int main()
- •Int main()
- •I can write anything I want in it */
- •1.5.9Indentation
- •Int main()
- •I can write anything I want in it */
- •1.5.10Escape Sequences
- •1.6Введение в классы
- •Int protect()
- •Int main()
- •1.7.1Source Files
- •1.7.2Practical Learning: Creating a Source File
- •1.7.3Header Files
- •1.7.4Practical Learning: Creating a Header File
- •Int ShowWelcome();
- •Int cProperty::ShowWelcome()
- •1.7.5Assemblies
- •1.7.6Applications
- •1.7.7The Public and Private Objects of an Assembly
- •1.7.8Practical Learning: Controlling the Assembly Access of a Class
- •1.7.9Creating a Class
- •1.7.10Practical Learning: Creating a Class
- •1.8The Code Editor
- •1.8.1 Description
- •1.8.2The Tabs Bar
- •1.8.3The Scopes Combo Box
- •1.8.4The Functions Combo Box
- •1.8.5Code Colors
- •1.9The Solution Explorer
- •1.9.1 Introduction
- •1.9.2 Using the Solution Explorer
- •1.10The Class View
- •1.10.1Introduction
- •1.10.2Using the Class View
- •1.11Namespaces and Code Directives
- •1.11.1Introduction
- •1.11.2Practical Learning: Including a Class in a Namespace
- •1.11.3Using a Namespace
- •Int drive()
- •Int main()
- •Int main()
- •1.11.4Using Various Namespaces
- •Int drive()
- •Int showroof()
- •Int drive()
- •Int main()
- •Int drive()
- •Int main()
- •Int drive()
- •Int main()
- •1.11.5Nesting Namespaces
- •Int main()
- •Int main()
- •1.11.6Built-In Namespaces
- •1.11.6.1 The System Namespace
- •Int main()
- •1.11.6.2The std Namespace
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •1.12C Routines
- •Int main()
- •1.13Primary Details of Program Structure
- •1.13.1Preprocessors: #include
- •1.13.2Preprocessors: #define
- •Int main()
- •1.14Pragma Directives
- •1.14.1 Introduction
- •1.14.2Open Once
- •2. Introduction to Variables
- •2.1Introduction
- •2.2The Stack
- •2.3Variable Declaration
- •2.5Keywords
- •Internal initonly interface literal long
- •Value virtual void volatile wchar_t
- •3.Data Types
- •3.1Variable Initialization
- •3.2Introduction to Data Types
- •3.3Practical Learning: Introducing Data Types Applications
- •Int main()
- •3.4Integers
- •3.4.1Signed and Unsigned Numbers
- •3.4.2Bytes
- •Int main()
- •Int main()
- •3.4.3Practical Learning: Declaring a Byte Variable
- •Int main()
- •3.4.4Short Variables
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •3.4.5Integral Variables
- •Int main()
- •3.4.6Practical Learning: Declaring Unsigned Variables
- •3.4.7Long Integers
- •Int main()
- •3.4.8Practical Learning: Declaring Long Integers
- •Int main()
- •3.4.9Initializing an Integral Variable
- •3.5Characters
- •3.5.1 Symbolic Characters
- •Int main()
- •Int main()
- •3.5.2Unicode Characters
- •Int main()
- •Int main()
- •3.5.3Practical Learning: Using Character Variables
- •Int main()
- •3.6The String: a List of Characters
- •Int main()
- •3.7Decimal Numbers
- •3.7.1Floating-Point Variables
- •Int main()
- •3.7.2Practical Learning: Using a Single-Precision Variables
- •Int main()
- •3.7.3Double-Precision Variables
- •Int main()
- •3.7.4Practical Learning: Using a Single-Precision Variables
- •Int main()
- •3.7.5Initializing a Double-Precision Variable
- •Int main()
- •Int main()
- •3.8Variable Reference
- •3.8.1 The typedef Type Definition
- •Int main()
- •Int main()
- •3.9Native References
- •Int &Mine;
- •Int main()
- •Int main()
- •Its reference: 228
- •Int main()
- •Its reference: 228
- •Its reference: -15008
- •Its reference: 28114
- •Int main()
- •Int main()
- •3.10A Tracking Reference (отслеживаемая ссылка)
- •Int main()
- •Int % PropertyValue;
- •Int main()
- •4. Techniques of Using Variables
- •4.1 Constant Values
- •4.1.1 Introduction
- •Int main()
- •Int main()
- •4.1.2Custom Constants
- •Int main()
- •Int main()
- •4.1.3Language Constants
- •Int main()
- •4.1.4Using #define
- •Int main()
- •Int main()
- •4.2Pointer Types
- •4.2.1 Introduction
- •Int main()
- •4.2.2Pointer Declaration
- •Int main()
- •Int *Number;
- •4.2.3Pointer Initialization
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int *Number;
- •Int main()
- •Int *Number;
- •4.2.4A Pointer to a Pointer
- •Int main()
- •Int *pointer;
- •Int main()
- •Int *pointer;
- •Int **pointerToPointer;
- •Int main()
- •Int *pointer;
- •Int **pointerToPointer;
- •Int main()
- •Int *pointer;
- •Int **pointerToPointer;
- •4.2.5Type Defining a Pointer
- •Int *pAge;
- •4.3Pointers and Memory Management
- •4.3.1 Introduction
- •Int main()
- •Int main()
- •Int main()
- •4.3.2The new Operator
- •Int main()
- •4.3.3Practical Learning: Introducing Pointers
- •Int main()
- •4.3.4The delete Operator
- •Int main()
- •4.3.5Practical Learning: Deleting Pointers
- •Int main()
- •4.4Handle Types
- •4.4.1 Introduction
- •4.4.2A Tracking Reference
- •Int main()
- •Int main()
- •4.4.3Creating a Handle (дескриптор)
- •Int main()
- •Int main()
- •Item Price:
- •4.5Using the Garbage Collector
- •Int main()
- •Int main()
- •Item Price: 148.95
- •Int main()
- •Int main()
- •Item Price: 148.95
- •Int main()
- •Int main()
- •Int main()
- •4.5.1Practical Learning: Using Handles
- •Int main()
- •5. Introduction to Classes
- •5.1 A Review of Classes
- •5.1.1 Introduction
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •5.1.2Practical Learning: Introducing Classes
- •Int main()
- •5.2Creating a Class
- •5.2.1Practical Learning: Creating a Class
- •5.3Value Types
- •5.3.1 Introduction
- •5.3.2Practical Learning: Creating a Value Class
- •5.3.3Creating a Value Type
- •5.3.4Techniques of Initializing an Object
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •5.3.5Practical Learning: Initializing an Object
- •Int main()
- •5.3.6Class Members Levels of Access
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •5.3.7Practical Learning: Controlling the Access to a Class
- •5.3.8Type-Defining a Class
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •5.3.9Constant Objects
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •5.4Union
- •5.4.1Introduction
- •Int YearBuilt;
- •Int YearBuilt;
- •Int main()
- •5.4.2Using a Union
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •6.2Introduction to Pointers to Classes
- •6.2.1Practical Learning: Introducing Pointers to Classes
- •6.2.2Accessing the Members of a Pointer to a Class
- •Int main()
- •Int main()
- •6.2.3Practical Learning: Accessing the Members of a Pointer to a Class
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •6.3Allocating Memory on the Native Heap
- •Int main()
- •6.3.1Practical Learning: Allocating Memory on the Native Heap
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int main()
- •6.3.3Practical Learning: De-Allocating Memory from the Native Heap
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •6.4Classes and Pointers to Pointers
- •6.4.1Declaring a Pointer to Pointer
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •6.5Handle Types
- •6.5.1 Introduction
- •6.5.2Practical Learning: Introducing Handles
- •Int main()
- •6.5.3A Tracking Reference
- •Int main()
- •6.5.4Creating a Handle
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.5.5Practical Learning: Creating a Handle
- •Int main()
- •6.6Reference Types
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.6.1Practical Learning: Creating a Reference Class
- •6.6.2Accessing the Members of a Handle
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.6.3Using the Garbage Collector
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.6.4Practical Learning: Initializing a Handle
- •Int main()
- •7.Classes Combinations and Inheritance
- •7.1Class Combinations (агрегирование классов)
- •7.1.1 A Class as a Member Variable
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int main()
- •7.1.2Practical Learning: Using an Object as a Field
- •7.1.3Introduction to Strings
- •Int main()
- •Int main()
- •7.1.4Practical Learning: Using String Variables
- •7.1.5A String as a Member Variable of a Class
- •7.1.6Practical Learning: Using Strings as Fields
- •7.2Inheritance
- •7.2.1 Introduction
- •7.2.2Practical Learning: Introducing Inheritance
- •7.2.3Inheriting From a Class
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Condition;
- •7.2.4Practical Learning: Inheriting From a Class
- •7.2.5The protected Access Level
- •Int Bedrooms;
- •Int YearBuilt;
- •7.2.6Namespaces and Inheritance
- •7.3The Object Class
- •7.3.1 Introduction
- •7.3.2An Object as a Handle
- •Int main()
- •Int main()
- •7.3.3Inheriting from the Object Class
- •7.3.4Practical Learning: Inheriting From the Object Class
- •8.Data Input/Output, Reading, and Formatting
- •8.1 Displaying Data
- •8.1.1 Introduction
- •8.1.2General Display With cout, Write(), and WriteLine()
- •Int main()
- •Int main()
- •8.1.3Data Display With puts()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •8.2.2Filling the Empty Space
- •Int main()
- •Int main()
- •8.2.3The dec, hex, and oct Operators
- •Int main()
- •Int main()
- •8.2.4The uppercase Attribute
- •8.2.5Setting the I/o Flag
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •8.2.7C How to Display Data
- •Int main()
- •Int main()
- •8.3Data Input
- •8.3.1Using cin
- •Int main()
- •Int Natural;
- •8.3.2C How to Input Data
- •8.4Accessories
- •8.4.1Exiting a Program
- •Int main()
- •8.4.2Aborting a Program
- •8.4.3Terminating a Program
- •8.4.4Clearing the Screen
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •8.5.1 Introduction
- •8.5.2Practical Learning: Introducing Data Reading
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Condition;
- •Int main()
- •8.5.3String Value Request
- •Int main()
- •8.5.4Character and Number Request
- •Int main()
- •Int Number;
- •8.5.5Practical Learning: Requesting Data
- •8.6Formatting Data Display
- •8.6.1 Introduction
- •Int main()
- •8.6.2Conversion To String
- •Int main()
- •8.6.3Number Formatting
- •Int main()
- •8.6.4Line Formatting
- •Int main()
- •8.6.5Practical Learning: Formatting Data
- •Int main()
- •9. Introduction to Functions
- •9.1 Functions
- •9.1.1 Definition
- •9.1.2Fundamentals of Creating a Function
- •Void Introduction() { Console::WriteLine(l"The Wonderful World of
- •Void Introduction()
- •Int main()
- •9.1.3Calling a Function
- •Void Introduction()
- •Int main()
- •Introduction();
- •Int main()
- •Void IdentifyHouse();
- •Void IdentifyHouse()
- •9.1.4Practical Learning: Introducing Functions
- •Void CreateAndShowProperty()
- •Int condition;
- •9.1.5Inline Functions
- •9.2Techniques of Returning a Value
- •9.2.1 Returning a Primitive Type
- •Int main()
- •9.2.2Practical Learning: Returning a Primitive Type
- •Int GetPropertyCondition()
- •Int condition;
- •Void CreateAndShowProperty()
- •Int condition;
- •Int main()
- •9.2.3Returning a Native Reference
- •Int main()
- •9.2.4Returning a Tracking Reference
- •Int main()
- •9.2.5Returning a Pointer
- •Int main()
- •9.2.6Returning a Handle
- •9.2.7Practical Learning: Returning a Handle
- •Void CreateAndShowProperty()
- •Int main()
- •9.3Introduction to Functions Parameters
- •9.3.1 Overview of Parameters
- •Int main()
- •9.3.2Arguments to a Function
- •Void SetGender(__wchar_t a);
- •Void CalculateRateAmount(double price, double rate)
- •9.3.3Practical Learning: Introducing Functions
- •Void ShowProperty(long propNbr, int cond, Byte levels,
- •9.3.4Static Variables
- •Void Starter(int y)
- •Int main()
- •Void Starter(int y)
- •Int main()
- •Void Starter(int y)
- •Int main()
- •10.Details on Passing Arguments
- •10.1 Common Techniques of Using Parameters
- •10.1.1 Function Overloading
- •Int main()
- •10.1.2Default Arguments
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •10.1.3Constant Arguments
- •Int main()
- •10.2Passing Arguments by Reference
- •10.2.1 Passing by Native Reference
- •Void Area(double &Side); // The argument is passed by reference
- •Void Area(double &);
- •10.2.2Passing by Constant Reference
- •Void DisplayResult(const double OrigPrice, const double DiscAmt,
- •10.2.3Passing by Tracking Reference
- •10.3Passing a Pointer as Argument
- •10.3.1 Introduction
- •Int main()
- •Int main()
- •Int main()
- •10.3.2Constant Pointers as Arguments
- •Int main()
- •10.3.3Passing a Pointer to a Pointer
- •10.3.4Passing an Argument as a Reference to a Pointer
- •Int main()
- •10.3.5Passing an Argument as a Handle
- •Int main()
- •11.Classes and Functions
- •11.1 Returning a Class Type
- •11.1.1 Returning a Tracking Reference
- •Int Doors;
- •Int Year;
- •Int main()
- •11.1.2Practical Learning: Introducing Data Reading
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Condition;
- •Int main()
- •11.1.3Returning a Handle
- •11.1.4Practical Learning: Returning a Handle
- •Int main()
- •11.2Passing a Class Type
- •11.2.1 Passing a Tracking Reference
- •Void DescribeProperty(cHouse % home);
- •Void Show(cCar % car)
- •11.2.2Passing a Handle
- •11.2.3Practical Learning: Passing a Handle
- •Int main()
- •11.2.4The Effect of Passing a Class as a Tracking Reference or as a Handle
- •Int Doors;
- •Int Year;
- •Int main()
- •11.2.5Passing a Handle as a Reference
- •Int Doors;
- •Int Year;
- •Int main()
- •Int Doors;
- •Int Year;
- •Int main()
- •11.3Using the String Class
- •11.3.1 Returning a String
- •Int main()
- •11.3.2Passing a String
- •Int main()
- •11.4Introduction to the Methods of a Class
- •11.4.1 Methods Fundamentals
- •11.4.2Practical Learning: Introducing Methods
- •Int main()
- •11.4.3Method Local Definition
- •Int Doors;
- •Int Year;
- •Void Build()
- •Int main()
- •11.4.4Practical Learning: Implementing a Method Locally
- •Void CreateStoreItem()
- •11.4.5Method Global Definition
- •Int Doors;
- •Int Year;
- •Void Build()
- •Void Show();
- •Void cCar::Show()
- •Int main()
- •11.4.6Practical Learning: Implementing Methods Globally
- •Void CreateStoreItem();
- •Void ItemDescription();
- •Void cStoreItem::CreateStoreItem()
- •Void cStoreItem::ItemDescription()
- •Int main()
- •Item Number: 624406
- •Item Number: 624406
- •11.4.7Inline Methods
- •11.5Class and Self Return
- •11.5.1 Introduction
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •11.5.2This Pointer
- •Void cHouse::Show()
- •11.5.3Practical Learning: Using the this Pointer
- •Void cStoreItem::CreateStoreItem()
- •0 If no discount): ");
- •Void cStoreItem::ItemDescription()
- •12.1.3Constant Arguments
- •Int main()
- •12.1.4Practical Learning: Passing Constant Arguments
- •0 If no discount): ");
- •Item Number: 204066
- •Item Number: 204066
- •12.1.5Private Methods
- •Void Show();
- •Void cBox::Show()
- •Int main()
- •12.1.6Protected Methods
- •12.2Static Members of a Class
- •12.2.1 Static Member Variables
- •Void cCar::Show()
- •Int main()
- •12.2.2Static Methods
- •Int Doors;
- •Int Year;
- •Void Build();
- •Int Doors;
- •Int Year;
- •Int main()
- •Int Doors;
- •Int Year;
- •Int main()
- •12.3Classes and Constants
- •12.3.1 Static Constants
- •Inside a ref class or value type
- •12.3.2Literal Constants
- •12.4Class Nesting
- •12.4.1 Introduction
- •12.4.2Implementing Methods of a Nested Class
- •13. Class Construction and Destruction
- •13.1 Class Construction
- •13.1.1 Method Initializer
- •Int Type;
- •Int Color;
- •Int main()
- •Int Type;
- •Int Color;
- •Void Initializer(int type, int color, __wchar_t arrange,
- •Void cFlower::Initializer(int tp, int clr,
- •13.1.2Practical Learning: Introducing Constructors
- •Int main()
- •13.1.3Default Constructor
- •Int Type;
- •Int Color;
- •Int Type;
- •Int Color;
- •Int main()
- •Int main()
- •Int Type;
- •Int Color;
- •13.1.4Practical Learning: Using the Default Constructor
- •13.1.5The Constructor Initializer
- •Int main()
- •13.1.6Practical Learning: Initializing Using the Default Constructor
- •Int main()
- •Item Number: 0
- •13.1.7Constructor Overloading
- •Int main()
- •13.1.8Practical Learning: Overloading the Constructor
- •Inline long cStoreItem::GetItemNumber()
- •Inline void cStoreItem::SetItemNumber(const long number)
- •13.1.9Techniques of Initializing With a Constructor
- •Int main()
- •13.1.10Practical Learning: Initializing With the Constructors
- •13.2The Copy Constructor
- •13.2.1 Copying an Object
- •Int main()
- •13.2.2Using a Copy Constructor
- •13.3Destructors
- •13.3.1Introduction
- •13.3.2Practical Learning: Creating a Destructor
- •13.3.3Object Destruction in the Native Heap
- •13.3.4Object Destruction and the Managed Heap
- •14. The Properties of a Class
- •14.1Properties Fundamentals
- •14.1.1Introduction
- •14.1.2Practical Learning: Introducing the Properties of a Class
- •Int main()
- •14.1.3Reference Methods
- •Int main()
- •Int main()
- •14.1.4A Property
- •14.2Types of Properties
- •14.2.1 Simple Properties
- •Void ShowCharacteristics(cRectangle %recto)
- •Int main()
- •Int main()
- •14.2.2Practical Learning: Creating Simple Properties
- •Int main()
- •Item Number: 0
- •Item Number: 513497
- •14.2.3Read-Only Properties
- •Int main()
- •14.2.4Practical Learning: Using Read-Only Properties of a Class
- •Int main()
- •14.2.5Write-Only Properties
- •Void set(double h) { }
- •Int main()
- •14.2.6Read/Write Properties
- •14.2.7Practical Learning: Using Read/Write Properties of a Class
- •Int main()
- •Information");
- •Item Number: 666802
- •Item Number: 666802
- •14.3Other Techniques of Implementing Properties
- •14.3.1 Static Properties
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •15.1.2Declaring a Pointer to Function
- •Int main()
- •Void (*SomethingToSay)(void);
- •Void MovieQuote()
- •Void MovieQuote()
- •Int main()
- •Void (*SomethingToSay)();
- •15.1.3A Function Pointer that Returns a Value
- •Int Addition()
- •Int main()
- •Int (*SomeNumber)();
- •15.1.4A Function Pointer With Arguments
- •15.1.5Type-Defining a Function Pointer
- •Int Addition(int a, int b)
- •Int main()
- •15.1.6A Pointer to a Function as Argument
- •Int main()
- •15.2Classes and Pointers to Functions
- •15.2.1A Pointer to Function as a Member Variable
- •Int main()
- •Int main()
- •15.3Delegates
- •15.3.1 Introduction
- •15.3.2Practical Learning: Introducing Delegates
- •Void Show();
- •Void cFlower::Show()
- •Int main()
- •15.3.3Delegate Declaration
- •15.3.4Practical Learning: Creating a Delegate
- •Int main()
- •15.3.5Techniques of Using a Delegate
- •Int main()
- •Int main()
- •Int main()
- •Void ShowResult()
- •Int main()
- •15.3.6Practical Learning: Creating a Delegate
- •Int main()
- •15.3.7Delegates Compositions
- •15.3.8A Delegate With One of More Arguments
- •Void ShowResult()
- •Int main()
- •15.3.9Practical Learning: Using an Argumentative Delegate
- •Void Show(const int qty);
- •Void cFlower::Show(const int qty)
- •Int main()
- •15.3.10A Delegate Passed as Argument
- •Void CircleCharacteristics()
- •Int main()
- •16. Introduction to Conditions
- •16.1Boolean Variables
- •16.1.1 Introduction
- •16.1.2Practical Learning: Introducing Conditions
- •Int get() { return _tp; }
- •Int get() { return _clr; }
- •Int get() { return _qty; }
- •Int type, color, qty;
- •16.1.3Declaring a Boolean Variable
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •16.1.4Retrieving the Value of a Boolean Variable
- •Int main()
- •If Yes, enter True. Otherwise enter False: true
- •16.1.5Creating a Boolean Member Variable
- •16.1.6 Boolean Arguments
- •16.1.7A Boolean Property
- •16.1.8 Practical Learning: Creating a Boolean Property
- •16.2Enumerations
- •16.2.1 Introduction
- •Int main()
- •Int main()
- •16.2.2 Indexing the Members of an Enumeration
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •16.2.3Declaring an Enumeration Variable
- •16.2.4Global Enumerations
- •16.2.5Enumerations and Assemblies
- •16.3Enumerations and Classes
- •16.3.1 An Enumeration as a Member Variable
- •16.3.2An Enumeration as a Class
- •16.3.4Practical Learning: Creating Enumerations
- •17. Conditional Operators
- •18. Conditional Statements
- •19. Counting and Looping
- •20. Strings
- •21. Techniques on Using Inheritance
- •22. Variable Scope and Casting
- •23. Templates
- •24. Generics
- •25.Введение в массивы
- •25.1 Описание
- •25.1.1 Определение
- •25.1.2Создание массива
- •Int main()
- •Int Numbers[5];
- •25.1.3Initializing an Array
- •Int main()
- •Int main()
- •25.1.4 Type Defining an Array
- •Int main()
- •25.2Arrays and Memory Management
- •25.2.1 Creating a Dynamic Array
- •Int main()
- •Int main()
- •25.2.2 Cleaning After an Array
- •Int main()
- •25.3Managed Arrays
- •25.3.1 Introduction
- •Int main()
- •Int main()
- •25.3.2Practical Learning: Introducing Arrays
- •Int main()
- •25.3.3An Array of Handles
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •25.3.4Practical Learning: Using an Array of Handles
- •Int main()
- •25.4Arrays and Functions
- •25.4.1 Returning an Array
- •Int main()
- •25.4.2Practical Learning: Returning Arrays
- •25.4.3Passing an Array as Argument
- •25.4.4Practical Learning: Passing an Array as Argument
- •26. Multi-Dimensional Arrays
- •26.1 Single and Two-Dimensional Arrays
- •26.1.1 Introduction
- •26.1.2Practical Learning: Introducing Multi-Dimensional Arrays
- •26.1.4Multi-Dimensional Arrays
- •26.2Introduction to Jagged Arrays
- •26.2.1 Introduction
- •26.2.2 Creating a Jagged Array
- •26.2.3 Initializing a Jagged Array
- •26.3Jagged Arrays and Functions
- •26.3.1Returning a Jagged Array
- •26.3.2Passing a Jagged Array as Argument
- •26.4Multi-Dimensional Jagged Arrays
- •26.4.1Two-Dimensional Jagged Arrays
- •26.4.2Multi-Dimensional Jagged Arrays
- •27.Arrays and Classes
- •27.1The Array Class
- •27.1.1 Introduction
- •27.1.2 The Length of an Array
- •Int main()
- •28.Introduction to File Processing
- •29.Details on File Processing
- •30.Files Operations
- •31.Serialization
- •32.Introduction to Indexed Properties
- •33.Classes and Indexed Properties
- •34.Введение в коллекции
- •34.1Коллекции на основе массива
- •34.1.1Вступление
- •34.1.2Объявление коллекции
- •Int main()
- •34.1.3 Количество элементов в коллекции
- •34.2Операции над коллекцией, основанной на массиве
- •34.2.1 Добавление элемента
- •Int size;
- •Int get() { return size; }
- •Int main()
- •34.2.2 Извлечение элемента из коллекции
- •Int size;
- •Int get() { return size; }
- •Int main()
- •34.2.3 Вставка элемента в коллекцию
- •Int size;
- •Int get() { return size; }
- •1. Список не заполнен до конца
- •2. Указанная позиция находится в допустимом диапазоне
- •Int main()
- •34.2.4 Удаление элемента из коллекции
- •Int size;
- •Int get() { return size; }
- •Int main()
- •34.3Коллекция элементов (заказ букета цветов)
- •34.3.1 Вступление
- •34.3.2Practical Learning: Introducing Collections
- •34.3.3 Implementing a Collection
- •34.3.4 Practical Learning: Creating a cCollection Class
- •34.3.5The Beginning of a Collection
- •34.3.6 Linking the Items of a Collection
- •34.3.7 Practical Learning: Creating a List's Monitor
- •34.4 Коллекции на основе списка (Operations on a Collection)
- •34.4.1 Adding an Item
- •34.4.2 Practical Learning: Adding Items to a Collection
- •34.4.3Retrieving an Item
- •34.4.4 Practical Learning: Retrieving the Items of a Collection
- •34.4.5 Removing an Item
- •34.4.6 Practical Learning: Retrieving the Items of a Collection
- •34.4.7 Locating an Item
- •35.Основы коллекций платформы .Net (Fundamentals of .Net Support For Collections)
- •35.1 Перечисление элементов коллекции (Enumerating the Members of a Collection)
- •35.1.1 Введение в коллекции System
- •35.1.2Практический пример
- •Int Mileage;
- •Int items;
- •Int get() { return items; }
- •Virtual bool Delete() override;
- •Items--;
- •35.1.3Introduction to the iEnumerator Interface
- •35.1.4 Упражнение
- •35.1.5 Текущий элемент перечисления
- •35.1.6Упражнение
- •Int curPosition;
- •35.1.7Сброс метки текущего элемента
- •Void Reset();
- •Virtual void Reset();
- •Void cEnumerator::Reset()
- •35.1.8 Упражнение
- •Int curPosition;
- •Virtual void Reset();
- •Void cCarIdentifier::Reset()
- •35.1.9Перемещение к следующему элементу в iEnumerator
- •Virtual void Reset();
- •Virtual bool MoveNext();
- •Void cEnumerator::Reset()
- •35.1.10Упражнение
- •Int curPosition;
- •Virtual void Reset();
- •Virtual bool MoveNext();
- •Void cCarIdentifier::Reset()
- •35.2Перечислимая коллекция (An Enumerable Collection)
- •35.2.1 Вступление
- •35.2.2 Получение Enumerator (Getting the Enumerator)
- •35.2.3Упражнение
- •36.Встроенные интерфейсы коллекций
- •36.1 Обзор интерфейсов коллекций
- •36.1.1 Вступление
- •36.1.2Choosing a Class or an Interface
- •36.2Интерфейс iCollection
- •36.2.1 Вступление
- •36.2.2Реализация iCollection
- •Int nbrOfStudents;
- •Virtual property int Count
- •Int get() { return nbrOfStudents; }
- •Int nbrOfItems;
- •Virtual property int Count
- •Int get() { return nbrOfItems; }
- •Int nbrOfItems;
- •Int nbrOfItems;
- •Virtual property bool IsSynchronized
- •Int nbrOfItems;
- •36.3Интерфейс iList
- •36.3.1Вступление
- •36.3.2Упражнение
- •Int main()
- •36.3.3Implementing iList
- •36.3.4 Упражнение
- •36.4Размер коллекции
- •36.4.1 Коллекция фиксированного размера
- •Int items;
- •Virtual property bool IsFixedSize
- •36.4.2 Упражнение
- •Int counter;
- •Virtual property bool IsFixedSize
- •36.4.3Коллекция только для чтения
- •36.4.4Упражнение
- •Int counter;
- •Virtual void RemoveAt(int index);
- •Virtual void Clear(void);
- •36.5Наполнение коллекции
- •36.5.1 Добавление элементов
- •Int items;
- •36.5.2Упражнение
- •Int main()
- •36.5.3Вставка элемента
- •36.5.4Упражнение
- •Int main()
- •36.6Размещение элемента в коллекции
- •36.6.1 Значение по умолчанию в коллекции
- •Int items;
- •36.6.2Упражнение
- •Int counter;
- •Int main()
- •36.6.3Проверка существования элемента в коллекции
- •Int items;
- •36.6.4 Упражнение: проверка наличия элемента в коллекции
- •Int main()
- •36.6.5Получение индекса элемента
- •Int items;
- •36.6.6Упражнение: получение индекса элемента
- •Int main()
- •36.7Удаление элементов коллекции
- •36.7.1 Удаление элемента по его индексу
- •37.Встроенные классы коллекций
- •37.1 Класс ArrayList
- •37.1.1 Вступление
- •37.1.2 Емкость списка (The Capacity of a List)
- •37.1.3Список только для чтения
- •37.1.4Добавление элементов
- •37.1.5 Число элементов в списке
- •37.1.6 Получение элементов списка
- •37.1.7Доступ к элементу списка
- •37.1.8Удаление элемента
- •37.2Хеш-таблицы
- •37.2.1Вступление
- •37.2.2Создание хеш-таблицы
- •37.2.3Доступ к элементам хеш-таблицы
- •If (!diGcs.Exists)
- •If (!File.Exists(strFilename))
- •If (!File.Exists(strFilename))
- •If (File.Exists(strFilename))
- •If (File.Exists(strFilename))
- •If (File.Exists(strFilename))
- •37.2.4Доступ к элементу хеш-таблицы
- •37.2.5Удаление элементов хеш-таблицы
- •37.3Стек
- •37.3.1 Вступление
- •37.3.2Создание стека
- •37.3.3Добавление элементов в стек
- •37.3.4Доступ к элементам стека
- •37.3.5Удаление элементов из стека
- •37.4Очередь
- •37.4.1Вступление
- •37.4.2Создание очереди
- •37.4.3Построение очереди (Building a Queue)
- •37.4.4Получение элементов очереди
- •37.4.5Удаление элементов из очереди
18. Conditional Statements
|
Conditions |
|
Introduction |
|
A conditional expression is an expression that produces a true or false result. You can then use that result as you see fit. To create the expression, you use the Boolean operators we studied in the previous lesson. In the previous lesson, we saw only how to perform the operations and how to get the results, not how to use them. To use the result of a Boolean operation, the C++ programming language provides some specific conditional operators.
|
|
Start Microsoft Visual C++ 2005
On the main menu, click File -> New -> Project...
On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
In the Name box, replace the string with ElectroStore6 and click OK
On the main menu, click Project -> Add Class...
In the Categories lists, expand Visual C++ and click C++. In the Templates list, make sure C++ Class is selected and click Add
Set the Name of the class to CStoreItem and click Finish
Complete the StoreItem.h header file as follows:
#pragma once
using namespace System;
public enum class ItemsCategories
{
Unknown,
CablesAndConnectors,
CellPhonesAndAccessories,
Headphones,
DigitalCameras,
PDAsAndAccessories,
TelephonesAndAccessories,
TVsAndVideos,
SurgeProtectors,
Instructional
};
namespace ElectronicsStore
{
public ref class CStoreItem
{
public:
// An item whose characteristics are not (yet) defined
CStoreItem(void);
// An item that is known by its make, model, and unit price
CStoreItem(long itmNbr, String ^ make,
String ^ model, double unitPrice);
// An item that is known by its name and unit price
CStoreItem(long itmNbr, String ^ name, double unitPrice);
// An item completely defined
CStoreItem(long itmNbr, ItemsCategories category,
String ^ make, String ^ model, double unitPrice);
~CStoreItem();
private:
long nbr;
ItemsCategories cat;
String ^ mk;
String ^ mdl;
String ^ nm;
double price;
public:
property long ItemNumber
{
long get() { return nbr; }
void set(long n) { this->nbr = n; }
}
property ItemsCategories Category
{
ItemsCategories get() { return cat; }
void set(ItemsCategories c) { this->cat = c; }
}
property String ^ Make
{
String ^ get() { return mk; }
void set(String ^ m) { this->mk = m; }
}
property String ^ Model
{
String ^ get() { return mdl; }
void set(String ^ m) { this->mdl = m; }
}
property String ^ Name
{
String ^ get() { return nm; }
void set(String ^ n) { this->nm = n; }
}
property double UnitPrice
{
double get() { return price; }
void set(double p) { this->price = p; }
}
};
}
Access the StoreItem.cpp source file and change it as follows:
#include "StoreItem.h"
namespace ElectronicsStore
{
CStoreItem::CStoreItem(void)
{
nbr = 0;
cat = ItemsCategories::Unknown;
mk = L"Unknown";
mdl = L"Unspecified";
nm = L"N/A";
price = 0.00;
}
CStoreItem::CStoreItem(long itmNbr, String ^ make,
String ^ model, double unitPrice)
{
nbr = itmNbr;
cat = ItemsCategories::Unknown;
mk = make;
mdl = model;
nm = L"N/A";
price = unitPrice;
}
CStoreItem::CStoreItem(long itmNbr, String ^ name,
double unitPrice)
{
nbr = itmNbr;
cat = ItemsCategories::Unknown;
mk = L"Unknown";
mdl = L"Unspecified";
nm = name;
price = unitPrice;
}
CStoreItem::CStoreItem(long itmNbr, ItemsCategories category,
String ^ make, String ^ model,
double unitPrice)
{
nbr = itmNbr;
cat = category;
mk = make;
mdl = model;
price = unitPrice;
}
CStoreItem::~CStoreItem()
{
}
}
To create one more source file, on the main menu, click Project -> Add New Item...
In the Templates list, make sure C++ File (.cpp) is selected. Set the Name to Exercise and click Add
Complete the file as follows:
#include "StoreItem.h"
using namespace System;
int main()
{
String ^ strTitle = L"=-= Nearson Electonics =-=\n"
L"******* Store Items ******";
Console::WriteLine();
return 0;
}
Execute the application to make sure it can compile
Close the DOS window
if a Condition is True |
|
Consider the following program:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
Console::WriteLine(L"\nType of Home: {0}", TypeOfHome);
Console::WriteLine();
return 0;
}
Here is an example of running the program:
What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? S
Type of Home: S
Press any key to continue . . .
To check if an expression is true and use its Boolean result, you can use the if operator. Its formula is:
if(Condition) Statement;
The Condition can be the type of Boolean operation we studied in the previous lesson. That is, it can have the following formula:
Operand1 BooleanOperator Operand2
If the Condition produces a true result, then the compiler executes the Statement. If the statement to execute is short, you can write it on the same line with the condition that is being checked. Here is an example:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
Console::Write(L"");
if(TypeOfHome == L'S') Console::WriteLine(L"\nType of Home: Single Family");
Console::WriteLine();
return 0;
}
Here is an example of running the program:
What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? S
Type of Home: Single Family
Press any key to continue . . .
If the Statement is too long, you can write it on a different line than the if condition. Here is an example:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
if(TypeOfHome == L'S')
Console::WriteLine(L"\nType of Home: Single Family");
Console::WriteLine();
return 0;
}
You can also write the Statement on its own line if the statement is short enough to fit on the same line with the Condition.
Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket “{“ and a closing curly bracket “}”. Here is an example:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
if(TypeOfHome == L'S')
{
Console::Write(L"\nType of Home: ");
Console::WriteLine(L"Single Family");
}
Console::WriteLine();
return 0;
}
If you omit the brackets, only the statement that immediately follows the condition would be executed. Just as you can write one if condition, you can write more than one. Here are examples:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
if(TypeOfHome == L'S')
Console::WriteLine(L"\nType of Home: Single Family");
if(TypeOfHome == L'T')
Console::WriteLine(L"\nType of Home: Town House");
if(TypeOfHome == L'C')
Console::WriteLine(L"\nType of Home: Condominium");
Console::WriteLine();
return 0;
}
Here is an example of running the program:
What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? C
Type of Home: Condominium
Press any key to continue . . .
Practical Learning: Using the Simple if Condition |
|
To use the if condition, change the contents of the Exercise.cpp source file as follows:
#include "StoreItem.h"
using namespace System;
using namespace ElectronicsStore;
CStoreItem ^ CreateStoreItem();
static void DescribeStoreItem(CStoreItem ^ %);
int main()
{
String ^ strTitle = L"=-= Nearson Electonics =-=\n"
L"******* Store Items ******";
CStoreItem ^ saleItem = CreateStoreItem();
Console::WriteLine(L"");
DescribeStoreItem(saleItem, 0);
Console::WriteLine();
return 0;
}
CStoreItem ^ CreateStoreItem()
{
CStoreItem ^ sItem = gcnew CStoreItem;
int category;
Console::WriteLine(L"To create a store item, enter its information");
Console::Write(L"Item Number: ");
sItem->ItemNumber = long::Parse(Console::ReadLine());
Console::WriteLine(L"Category");
Console::WriteLine(L"1. Unknown/Miscellaneous");
Console::WriteLine(L"2. Cables and Connectors");
Console::WriteLine(L"3. Cell Phones and Accessories");
Console::WriteLine(L"4. Headphones");
Console::WriteLine(L"5. Digital Cameras");
Console::WriteLine(L"6. PDAs and Accessories");
Console::WriteLine(L"7. Telephones and Accessories");
Console::WriteLine(L"8. TVs and Videos - Plasma / LCD");
Console::WriteLine(L"9. Surge Protector");
Console::WriteLine(L"10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
Console::Write(L"Your Choice? ");
category = int::Parse(Console::ReadLine());
if( category == 1 )
sItem->Category = ItemsCategories::Unknown;
if( category == 2 )
sItem->Category = ItemsCategories::CablesAndConnectors;
if( category == 3 )
sItem->Category = ItemsCategories::CellPhonesAndAccessories;
if( category == 4 )
sItem->Category = ItemsCategories::Headphones;
if( category == 5 )
sItem->Category = ItemsCategories::DigitalCameras;
if( category == 6 )
sItem->Category = ItemsCategories::PDAsAndAccessories;
if( category == 7 )
sItem->Category = ItemsCategories::TelephonesAndAccessories;
if( category == 8 )
sItem->Category = ItemsCategories::TVsAndVideos;
if( category == 9 )
sItem->Category = ItemsCategories::SurgeProtectors;
if( category == 10 )
sItem->Category = ItemsCategories::Instructional;
Console::Write(L"Make ");
sItem->Make = Console::ReadLine();
Console::Write(L"Model: ");
sItem->Model = Console::ReadLine();
Console::Write(L"Unit Price: ");
sItem->UnitPrice = double::Parse(Console::ReadLine());
return sItem;
}
void DescribeStoreItem(CStoreItem ^ %item)
{
Console::WriteLine(L"Store Item Description");
Console::WriteLine(L"Item Number: {0}", item->ItemNumber);
Console::WriteLine(L"Category: {0}", item->Category);
Console::WriteLine(L"Make {0}", item->Make);
Console::WriteLine(L"Model: {0}", item->Model);
Console::WriteLine(L"Unit Price: {0:C}", item->UnitPrice);
}
Execute the application to see the result. Here is an example:
To create a store item, enter its information
Item Number: 237875
Category
1. Unknown/Miscellaneous
2. Cables and Connectors
3. Cell Phones and Accessories
4. Headphones
5. Digital Cameras
6. PDAs and Accessories
7. Telephones and Accessories
8. TVs and Videos - Plasma / LCD
9. Surge Protector
10. Instructional and Tutorials (VHS & DVD)TVs and Videos
Your Choice? 4
Make Tritton
Model: AX360
Unit Price: 145.85
Store Item Description
Item Number: 237875
Category: Headphones
Make Tritton
Model: AX360
Unit Price: $145.85
Press any key to continue . . .
Close the DOS window
if…else |
|
If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. As we saw in the previous section, any other result would be ignored. To address an alternative to an if condition, you can use the else condition. The formula to follow is:
if(Condition)
Statement1;
else
Statement2;
Once again, the Condition can be a Boolean operation like those we studied in the previous lesson. If the Condition is true, then the compiler would execute Statement1. If the Condition is false, then the compiler would execute Statement2. Here is an example:
using namespace System;
int main()
{
Byte Stories;
Console::Write(L"What's the maximum number of levels you want? ");
Stories = Byte::Parse(Console::ReadLine());
if(Stories == 1 )
Console::WriteLine(L"\nMaximum Levels: Single Level");
else
Console::WriteLine(L"\nMaximum Levels: Any Number");
Console::WriteLine();
return 0;
}
Here is an example of running the program:
What's the maximum number of levels you want? 3
Maximum Levels: Any Number
Press any key to continue . . .
Here is another example of running the program:
What's the maximum number of levels you want? 1
Maximum Levels: Single Level
Press any key to continue . . .
Practical Learning: Using the if...else Condition |
|
Access the StoreItem.h header file
To use the if...else condition, change the UnitPrice property as follows:
#pragma once
using namespace System;
. . .
namespace ElectronicsStore
{
public ref class CStoreItem
{
public:
. . .
private:
long nbr;
ItemsCategories cat;
String ^ mk;
String ^ mdl;
String ^ nm;
double price;
public:
. . .
property double UnitPrice
{
double get() { return price; }
void set(double p)
{
if( p <= 0 )
this->price = 0.00;
else
this->price = p;
}
}
};
}
Access the Exercise.cpp file and change it as follows:
#include "StoreItem.h"
using namespace System;
using namespace ElectronicsStore;
CStoreItem ^ CreateStoreItem();
static void DescribeStoreItem(CStoreItem ^ %);
static void DescribeStoreItem(CStoreItem ^ %, const int);
int main()
{
String ^ strTitle = L"=-= Nearson Electonics =-=\n"
L"******* Store Items ******";
CStoreItem ^ saleItem = CreateStoreItem();
Console::WriteLine(L"");
if( saleItem->Category == ItemsCategories::Unknown )
DescribeStoreItem(saleItem, 0);
else
DescribeStoreItem(saleItem);
Console::WriteLine();
return 0;
}
CStoreItem ^ CreateStoreItem()
{
CStoreItem ^ sItem = gcnew CStoreItem;
int category;
Console::WriteLine(L"To create a store item, enter its information");
Console::Write(L"Item Number: ");
sItem->ItemNumber = long::Parse(Console::ReadLine());
Console::WriteLine(L"Category");
Console::WriteLine(L"1. Unknown/Miscellaneous");
Console::WriteLine(L"2. Cables and Connectors");
Console::WriteLine(L"3. Cell Phones and Accessories");
Console::WriteLine(L"4. Headphones");
Console::WriteLine(L"5. Digital Cameras");
Console::WriteLine(L"6. PDAs and Accessories");
Console::WriteLine(L"7. Telephones and Accessories");
Console::WriteLine(L"8. TVs and Videos - Plasma / LCD");
Console::WriteLine(L"9. Surge Protector");
Console::WriteLine(L"10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
Console::Write(L"Your Choice? ");
category = int::Parse(Console::ReadLine());
// If the user specifies that the type is not known
// then we need only the name/description of the item
if( category == 1 )
{
sItem->Category = ItemsCategories::Unknown;
Console::Write(L"Enter the item name or description: ");
sItem->Name = Console::ReadLine();
}
else
{
if( category == 2 )
sItem->Category = ItemsCategories::CablesAndConnectors;
if( category == 3 )
sItem->Category = ItemsCategories::CellPhonesAndAccessories;
if( category == 4 )
sItem->Category = ItemsCategories::Headphones;
if( category == 5 )
sItem->Category = ItemsCategories::DigitalCameras;
if( category == 6 )
sItem->Category = ItemsCategories::PDAsAndAccessories;
if( category == 7 )
sItem->Category = ItemsCategories::TelephonesAndAccessories;
if( category == 8 )
sItem->Category = ItemsCategories::TVsAndVideos;
if( category == 9 )
sItem->Category = ItemsCategories::SurgeProtectors;
if( category == 10 )
sItem->Category = ItemsCategories::Instructional;
// If the user selected a category other than Unknown
// then ask the make and model of the item
Console::Write(L"Make ");
sItem->Make = Console::ReadLine();
Console::Write(L"Model: ");
sItem->Model = Console::ReadLine();
}
Console::Write(L"Unit Price: ");
sItem->UnitPrice = double::Parse(Console::ReadLine());
return sItem;
}
// This function is used when an item is specified by its make and model
void DescribeStoreItem(CStoreItem ^ %item)
{
Console::WriteLine(L"Store Item Description");
Console::WriteLine(L"Item Number: {0}", item->ItemNumber);
Console::WriteLine(L"Category: {0}", item->Category);
Console::WriteLine(L"Make {0}", item->Make);
Console::WriteLine(L"Model: {0}", item->Model);
Console::WriteLine(L"Unit Price: {0:C}", item->UnitPrice);
}
// This function is used when an item is specified by its name
void DescribeStoreItem(CStoreItem ^ %item, const int)
{
Console::WriteLine(L"Store Item Description");
Console::WriteLine(L"Item Number: {0}", item->ItemNumber);
Console::WriteLine(L"Category: Miscellaneous/Accessories");
Console::WriteLine(L"Name: {0}", item->Name);
Console::WriteLine(L"Unit Price: {0:C}", item->UnitPrice);
}
Execute the application to test it. After enter the item number, select a category other than 1 and continue with the rest. Here is an example:
To create a store item, enter its information
Item Number: 204006
Category
1. Unknown/Miscellaneous
2. Cables and Connectors
3. Cell Phones and Accessories
4. Headphones
5. Digital Cameras
6. PDAs and Accessories
7. Telephones and Accessories
8. TVs and Videos - Plasma / LCD
9. Surge Protector
10. Instructional and Tutorials (VHS & DVD)TVs and Videos
Your Choice? 5
Make Kodak
Model: Easyshare CD33
Unit Price: 69.95
Store Item Description
Item Number: 204006
Category: DigitalCameras
Make Kodak
Model: Easyshare CD33
Unit Price: $69.95
Press any key to continue . . .
Close the DOS window
Execute the application again. After enter the item number, enter 1 for the category and continue with the rest. Here is an example:
To create a store item, enter its information
Item Number: 268240
Category
1. Unknown/Miscellaneous
2. Cables and Connectors
3. Cell Phones and Accessories
4. Headphones
5. Digital Cameras
6. PDAs and Accessories
7. Telephones and Accessories
8. TVs and Videos - Plasma / LCD
9. Surge Protector
10. Instructional and Tutorials (VHS & DVD)TVs and Videos
Your Choice? 1
Enter the item name or description: VoIP Startup Kit
Unit Price: 88.85
Store Item Description
Item Number: 268240
Category: Miscellaneous/Accessories
Name: VoIP Startup Kit
Unit Price: $88.85
Press any key to continue . . .
Close the Dos window
The Ternary Operator (?:) |
|
The ternary operator behaves like a simple if…else statement. Its formula is:
Condition ? Statement1 : Statement2;
Here is an example:
using namespace System;
int main()
{
Byte Stories;
Console::Write(L"What's the maximum number of levels you want? ");
Stories = Byte::Parse(Console::ReadLine());
(Stories == 1) ?
Console::WriteLine(L"\nSingle Level") :
Console::WriteLine(L"\nAny Number of Levels");
Console::WriteLine();
return 0;
}
In Lesson 4, we saw different techniques of creating a constant. We saw that a constant must be initialized when it is created. In some cases, the constant you want to apply to a variable may depend on other variables. You cannot just use a conditional statement to control the value of a constant. The ternary operator provides an alternate solution to this problem. To use it, create a ?: operation and assign it to the constant variable. Here is an example:
using namespace System;
int main()
{
int x = 258;
const double y = (x <= 255 ? 1550.95 : 450.75);
Console::WriteLine(L"x = {0}", x);
Console::WriteLine(L"y = {0:F}", y);
Console::WriteLine();
return 0;
}
This would produce:
x = 258
y = 450.75
Press any key to continue . . .
Practical Learning: Using the Ternary Operator |
|
On the main menu, click File -> New -> Project...
On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
In the Name box, replace the string with FlowerShop3 and click OK
On the main menu, click Project -> Add Class...
In the Categories lists, expand Visual C++ and click C++. In the Templates list, make sure C++ Class is selected and click Add
Set the Name of the class to CFlower and click Finish
Complete the Flower.h header file as follows:
#pragma once
public enum class FlowerType
{
Roses = 1,
Lilies,
Daisies,
Carnations,
LivePlant,
Mixed
};
public enum class FlowerColor
{
Red = 1,
White,
Yellow,
Pink,
Orange,
Blue,
Lavender,
Mixed
};
public enum class FlowerArrangement
{
Bouquet = 1,
Vase,
Basket,
Mixed
};
public ref class CFlower
{
private:
int _tp;
int _clr;
int _arg;
bool _mx;
double _price;
public:
property int Type
{
int get() { return _tp; }
void set(int tp)
{
_tp = (tp <= 0 ? 0 : tp);
}
}
property int Color
{
int get() { return _clr; }
void set(int clr)
{
_clr = (clr <= 0 ? 0 : clr);
}
}
property int Arrangement
{
int get() { return _arg; }
void set(int arg)
{
_arg = (arg <= 0 ? 0 : arg);
}
}
property bool Mixed
{
bool get() { return _mx; }
void set(bool mx) { _mx = mx; }
}
property double UnitPrice
{
double get() { return _price; }
void set(double price)
{
_price = (price <= 0.00 ? 0.00 : price);
}
}
public:
CFlower(void);
CFlower(int type, int color,
int argn, bool mx, double price);
~CFlower();
};
Complete the Flower.cpp source file as follows:
#include "Flower.h"
CFlower::CFlower(void)
: _tp(0), _clr(0),
_arg(0), _mx(false),
_price(45.95)
{
}
CFlower::CFlower(int type, int color,
int argn, bool mx,
double price)
: _tp(type),
_clr(color),
_arg(argn),
_mx(mx),
_price(price)
{
}
CFlower::~CFlower()
{
}
On the main menu, click Project -> Add Class...
In the Templates list, make sure C++ Class is selected and click Add
Set the Name of the class to COrderProcessing and click Finish
Complete the OrderProcessing.h header file as follows:
#pragma once
#include "Flower.h"
public ref class COrderProcessing
{
private:
int _qty;
CFlower ^ _flr;
public:
COrderProcessing(void);
~COrderProcessing();
property CFlower ^ Flower
{
CFlower ^ get() { return _flr; }
void set(CFlower ^ flr) { _flr = flr; }
}
property int Quantity
{
int get() { return _qty; }
void set(int q)
{
_qty = (q <= 0 ? 0 : q);
}
}
double GetTotalPrice();
};
Complete the OrderProcessing.cpp source file as follows:
#include "OrderProcessing.h"
COrderProcessing::COrderProcessing(void)
{
_flr = gcnew CFlower;
}
COrderProcessing::~COrderProcessing()
{
delete _flr;
}
double COrderProcessing::GetTotalPrice()
{
return Quantity * _flr->UnitPrice;
}
To create one more source file, on the main menu, click Project -> Add New Item...
In the Templates list, make sure C++ File (.cpp) is selected. Set the Name to Exercise and click Add
Complete the file as follows:
#include "Flower.h"
#include "OrderProcessing.h"
using namespace System;
COrderProcessing ^ CreateFlowerOrder()
{
double price;
int arrangement;
int type, color, qty, mx;
COrderProcessing ^ order = gcnew COrderProcessing;
Console::WriteLine(L"=======================");
Console::WriteLine(L"==-=-=Flower Shop=-=-==");
Console::WriteLine(L"-----------------------");
Console::WriteLine(L"Enter the Type of Flower Order");
Console::WriteLine(L"1. Roses");
Console::WriteLine(L"2. Lilies");
Console::WriteLine(L"3. Daisies");
Console::WriteLine(L"4. Carnations");
Console::WriteLine(L"5. Live Plant");
Console::WriteLine(L"6. Mixed");
Console::Write(L"Your Choice: ");
type = int::Parse(Console::ReadLine());
Console::WriteLine(L"Enter the Color");
Console::WriteLine(L"1. Red");
Console::WriteLine(L"2. White");
Console::WriteLine(L"3. Yellow");
Console::WriteLine(L"4. Pink");
Console::WriteLine(L"5. Orange");
Console::WriteLine(L"6. Blue");
Console::WriteLine(L"7. Lavender");
Console::WriteLine(L"8. Mixed");
Console::Write(L"Your Choice: ");
color = int::Parse(Console::ReadLine());
Console::WriteLine(L"Enter the Type of Arrangement");
Console::WriteLine(L"1. Bouquet");
Console::WriteLine(L"2. Vase");
Console::WriteLine(L"3. Basket");
Console::WriteLine(L"4. Mixed");
Console::Write(L"Your Choice: ");
arrangement = int::Parse(Console::ReadLine());
Console::Write(L"Is the Order Mixed (1=Yes/0=No)?");
mx = int::Parse(Console::ReadLine());
Console::Write(L"Enter the Unit Price: ");
price = double::Parse(Console::ReadLine());
Console::Write(L"Enter Quantity: ");
qty = int::Parse(Console::ReadLine());
CFlower ^ flr = gcnew CFlower(type, color, arrangement,
mx = 1 ? true : false, price);
order->Flower = flr;
order->Quantity = qty;
return order;
}
int main()
{
COrderProcessing ^ flower = CreateFlowerOrder();
Console::WriteLine();
return 0;
}
Save all
if…else if and if…else if…else |
|
If you use an if...else conditional statement, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:
if(Condition1)
Statement1;
else if(Condition2)
Statement2;
The compiler would first check Condition1. If Condition1 is true, then Statement1 would be executed. If Condition1 is false, then the compiler would check Condition2. If Condition2 is true, then the compiler would execute Statement2. Any other result would be ignored. Here is an example:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
if( TypeOfHome == L'S' )
Console::WriteLine(L"\nType of Home: Single Family");
else if( TypeOfHome == L'T')
Console::WriteLine(L"\nType of Home: Town House");
Console::WriteLine();
return 0;
}
Here is an example of running the program:
What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? S
Type of Home: Single Family
Press any key to continue . . .
Here is another example of running the program:
What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? W
Press any key to continue . . .
Notice that only two conditions are evaluated. Any condition other than these two is not considered. Because there can be other alternatives, the C++ language provides an alternate else as the last resort. Its formula is:
if(Condition1) Statement1; else if(Condition2) Statement2; else Statement-n; |
|
|
if(Condition1) Statement1; else if(Condition2) Statement2; else if(Condition3) Statement3; else Statement-n; |
The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. Here is an example:
using namespace System;
int main()
{
__wchar_t TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"S - Single Family");
Console::WriteLine(L"T - Town House");
Console::WriteLine(L"C - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = __wchar_t::Parse(Console::ReadLine());
if( TypeOfHome == L'S' )
Console::WriteLine(L"\nType of Home: Single Family");
else if( TypeOfHome == L'T')
Console::WriteLine(L"\nType of Home: Town House");
else if( TypeOfHome == L'C')
Console::WriteLine(L"\nType of Home: Condominium");
else
Console::WriteLine(L"\nType of Home: Unknown");
Console::WriteLine();
return 0;
}
Here is an example of running the program:
What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? W
Type of Home: Unknown
Press any key to continue . . .
switch |
|
The if...else if...else statement allows you to create a series of conditions that would be checked one after another until either a valid one is found or the compiler has to execute a statement that doesn't fit any of the conditions. Instead of checking each condition, the C++ language provides a technique presenting one condition and some available options. Instead of checking each condition, the compiler can be directly lead to the appropriate statement. This is done using a switch operator.
The switch statement considers a condition and executes a statement based on the possible outcome. This possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The formula of the switch statement is:
switch(Expression)
{
case Choice1:
Statement1;
case Choice2:
Statement2;
case Choice-n:
Statement-n;
}
The expression to examine is an integer. Since an enumeration (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:
using namespace System;
int main()
{
int TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"1 - Single Family");
Console::WriteLine(L"2 - Town House");
Console::WriteLine(L"3 - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = int::Parse(Console::ReadLine());
switch(TypeOfHome)
{
case 1:
Console::WriteLine(L"\nType of Home: Single Family");
case 2:
Console::WriteLine(L"\nType of Home: Town House");
case 3:
Console::WriteLine(L"\nType of Home: Condominium");
}
Console::WriteLine();
return 0;
}
The program above would request a number from the user. If the user types 1, it would execute the first, the second, and the third cases. If the user types 2, the program would execute the second and third cases. If the user supplies 3, only the third case would be considered. If the user types any other number, no case would execute.
When establishing the possible outcomes that the switch statement should consider, at times there will be other possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The formula of the switch statement that considers the default case would be:
switch(Expression)
{
case Choice1:
Statement1;
case Choice2:
Statement2;
case Choice-n:
Statement-n;
default:
Other-Possibility;
}
Therefore another version of the program above would be:
using namespace System;
int main()
{
int TypeOfHome;
Console::WriteLine(L"What Type of House Would you Like to Purchase?");
Console::WriteLine(L"1 - Single Family");
Console::WriteLine(L"2 - Town House");
Console::WriteLine(L"3 - Condominium");
Console::Write(L"Your Choice? ");
TypeOfHome = int::Parse(Console::ReadLine());
switch(TypeOfHome)
{
case 1:
Console::WriteLine(L"\nType of Home: Single Family");
case 2:
Console::WriteLine(L"\nType of Home: Town House");
case 3:
Console::WriteLine(L"\nType of Home: Condominium");
default:
Console::WriteLine(L"\nType of Home:: Unknown");
}
Console::WriteLine();
return 0;
}
