Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Руководство_по_C++_CLI.doc
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
8.1 Mб
Скачать

34.3Коллекция элементов (заказ букета цветов)

34.3.1 Вступление

Как и массив, коллекция представляет собой совокупность элементов одного и того же типа. Особенностью создания массива является то, что вы должны заранее знать количество элементов, которые будут составлять список. Бывают случаи, когда вы не знаете, вы не можете знать, или вы не можете предсказать количество элементов списка. По этой причине вы можете создать список, для которого вы не указываете максимальное количество элементов, но позволяете пользователю списка возможность добавления, поиска или удаления элементов.

Перед тем как создать список, вы, вероятно, должны сначала решить, какие сущности будут элементами списка. Выше рассматривался список может из числовых значений. Вы можете создать список, который содержит имена. Такой список может быть создан из класса, который включает в себя строки. Иной тип списка может содержать сложные объекты.

34.3.2Practical Learning: Introducing Collections

  1. Start Microsoft Visual C++ and create a new CLR Empty Project named FlowerShop4

  2. To create a new class, in the Solution Explorer, right-click FlowerShop4 -> Add -> Class...

  3. In the Templates list, click C++ Class and click Add

  4. Set the Name of the class to CFlower and click Finish

  5. Change the Flower.h header file as follows:  

    using namespace System;

    public enum FlowerType

    {

    Roses = 1,

    Lilies,

    Daisies,

    Carnations,

    LivePlant,

    Mixed

    };

    public enum FlowerColor

    {

    Red = 1,

    White,

    Yellow,

    Pink,

    Orange,

    Blue,

    Lavender,

    Various

    };

  6. public enum FlowerArrangement

    {

    Bouquet = 1,

    Vase,

    Basket,

    Any

    };

    public ref class CFlower sealed

    {

    private:

    double pc;

    public:

    FlowerType Type;

    FlowerColor Color;

    FlowerArrangement Arrangement;

    property double UnitPrice

    {

    double get() { return pc; }

    void set(double value) { pc = value; }

    }

    CFlower();

    };

  7. Access the Flower.cpp source file and change it as follows:  

    #include "Flower.h"

    CFlower::CFlower(void)

    {

    Type = FlowerType::Mixed;

    Color = FlowerColor::Mixed;

    Arrangement = FlowerArrangement::Vase;

    pc = 0.00;

    }

  8. To create a new class, in the Solution Explorer, right-click FlowerShop4 -> Add -> Class...

  9. In the Templates list, click C++ Class and click Add

  10. Set the Name of the class to COrderProcessing and click Add

  11. Complete the OrderProcessing.h header file as follows:  

    #pragma once

    #include "Flower.h"

    using namespace System;

    public ref class COrderProcessing

    {

    public:

    CFlower ^ FlowerOrder;

    private:

    int qty;

    public:

    COrderProcessing(void);

    property int Quantity

    {

    int get() { return qty; }

    void set(int value) { qty = value; }

    }

    property double TotalPrice

    {

    double get() { return Quantity * FlowerOrder->UnitPrice; }

    }

    void GetFlowerType();

    void GetFlowerColor();

    void GetFlowerArrangement();

    void ProcessOrder()

    void ShowOrder();

    };

  12. Access the OrderProcessing.cpp source file and change it as follows:  

    #include "OrderProcessing.h"

    COrderProcessing::COrderProcessing(void)

    {

    FlowerOrder = gcnew CFlower;

    }

    void COrderProcessing::GetFlowerType()

    {

    int choice = 0;

    do {

    try {

    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("Your Choice: ");

    choice = int::Parse(Console::ReadLine());

    }

    catch(FormatException ^)

    {

    Console::WriteLine(L"You failed to enter an "

    L"appropriate number!");

    }

    if ((choice < 1) || (choice > 6))

    Console::WriteLine(L"Invalid Value: Please enter "

    L"a value between 1 and 6");

    } while( (choice < 1) || (choice > 6) );

    switch(choice)

    {

    case 1:

    FlowerOrder->Type = Roses;

    break;

    case 2:

    FlowerOrder->Type = Lilies;

    break;

    case 3:

    FlowerOrder->Type = Daisies;

    break;

    case 4:

    FlowerOrder->Type = Carnations;

    break;

    case 5:

    FlowerOrder->Type = LivePlant;

    break;

    default:

    FlowerOrder->Type = Mixed;

    break;

    }

    }

    void COrderProcessing::GetFlowerColor()

    {

    int choice = 0;

    do {

    try {

    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("Your Choice: ");

    choice = int::Parse(Console::ReadLine());

    }

    catch(FormatException ^)

    {

    Console::WriteLine(L"You didn't enter an "

    L"appropriate number!");

    }

    if( (choice < 1) || (choice > 8) )

    Console::WriteLine(L"Invalid Value: Please "

    L"enter a value between 1 and 8");

    } while ((choice < 1) || (choice > 8));

    switch(choice)

    {

    case 1:

    FlowerOrder->Color = Red;

    break;

    case 2:

    FlowerOrder->Color = White;

    break;

    case 3:

    FlowerOrder->Color = Yellow;

    break;

    case 4:

    FlowerOrder->Color = Pink;

    break;

    case 5:

    FlowerOrder->Color = Yellow;

    break;

    case 6:

    FlowerOrder->Color = Blue;

    break;

    case 7:

    FlowerOrder->Color = Lavender;

    break;

    default:

    FlowerOrder->Color = Various;

    break;

    }

    }

    void COrderProcessing::GetFlowerArrangement()

    {

    int choice = 0;

    do {

    try {

    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("Your Choice: ");

    choice = int::Parse(Console::ReadLine());

    }

    catch(FormatException ^)

    {

    Console::WriteLine(L"You didn't provide an "

    L"acceptable number!");

    }

    if( (choice < 1) || (choice > 4) )

    Console::WriteLine(L"Invalid Value: Please enter "

    L"a value between 1 and 4");

    } while ((choice < 1) || (choice > 4));

    switch (choice)

    {

    case 1:

    FlowerOrder->Arrangement = Bouquet;

    break;

    case 2:

    FlowerOrder->Arrangement = Vase;

    break;

    case 3:

    FlowerOrder->Arrangement = Basket;

    break;

    default:

    FlowerOrder->Arrangement = Any;

    break;

    }

    }

    void COrderProcessing::ProcessOrder()

    {

    GetFlowerType();

    GetFlowerColor();

    GetFlowerArrangement();

    try {

    Console::Write("Enter the Unit Price: ");

    FlowerOrder->UnitPrice =

    Math::Abs(double::Parse(Console::ReadLine()));

    }

    catch(FormatException ^)

    {

    Console::WriteLine(L"You didn't specify a valid price!");

    }

    try {

    Console::Write("Enter Quantity: ");

    Quantity = Math::Abs(int::Parse(Console::ReadLine()));

    }

    catch(FormatException ^)

    {

    Console::WriteLine(L"The quantity you entered "

    L"is not acceptable!");

    }

    }

    void COrderProcessing::ShowOrder()

    {

    Console::WriteLine(L"=======================");

    Console::WriteLine(L"==-=-=Flower Shop=-=-==");

    Console::WriteLine(L"-----------------------");

    Console::Write(L"Flower Type: ");

    switch(FlowerOrder->Type)

    {

    case 1:

    Console::WriteLine(L"Roses");

    break;

    case 2:

    Console::WriteLine(L"Lilies");

    break;

    case 3:

    Console::WriteLine(L"Daisies");

    break;

    case 4:

    Console::WriteLine(L"Carnations");

    break;

    case 5:

    Console::WriteLine(L"Live Plant");

    break;

    default:

    Console::WriteLine(L"Mixed");

    }

    Console::Write(L"Flower Color: ");

    switch(FlowerOrder->Color)

    {

    case 1:

    Console::WriteLine(L"Red");

    break;

    case 2:

    Console::WriteLine(L"White");

    break;

    case 3:

    Console::WriteLine(L"Yellow");

    break;

    case 4:

    Console::WriteLine(L"Pink");

    break;

    case 5:

    Console::WriteLine(L"Orange");

    break;

    case 6:

    Console::WriteLine(L"Blue");

    break;

    case 7:

    Console::WriteLine(L"Lavender");

    break;

    default:

    Console::WriteLine(L"Various");

    }

    Console::Write(L"Arrangement: ");

    switch(FlowerOrder->Arrangement)

    {

    case 1:

    Console::WriteLine(L"Bouquet");

    break;

    case 2:

    Console::WriteLine(L"Vase");

    break;

    case 3:

    Console::WriteLine(L"Basket");

    break;

    default:

    Console::WriteLine(L"Any");

    }

    Console::Write(L"Price: ");

    Console::WriteLine(FlowerOrder->UnitPrice);

    Console::Write(L"Quantity: ");

    Console::WriteLine(Quantity);

    Console::Write(L"Total Price: ");

    Console::WriteLine(TotalPrice.ToString(L"C"));

    Console::WriteLine(L"=======================");

    }

  13. To create a source file, in the Solution Explorer, right-click FlowerShop4 -> Add -> New Item...

  14. In the Templates list, click C++ File (.cpp)

  15. Set the Name to Exercise and click Add

  16. Complete the file as follows:  

    using namespace System;

    int main()

    {

    COrderProcessing ^ order = gcnew OrderProcessing;

    order->ProcessOrder();

    Console::WriteLine();

    order->ShowOrder();

    Console::WriteLine();

    return 0;

    }

  17. Execute the application and test it. Here is an example:  

    Enter the Type of Flower Order

    1. Roses

    2. Lilies

    3. Daisies

    4. Carnations

    5. Live Plant

    6. Mixed

    Your Choice: 3

    Enter the Color

    1. Red

    2. White

    3. Yellow

    4. Pink

    5. Orange

    6. Blue

    7. Lavender

    8. Mixed

    Your Choice: 8

    Enter the Type of Arrangement

    1. Bouquet

    2. Vase

    3. Basket

    4. Mixed

    Your Choice: 1

    Enter the Unit Price: 45.50

    Enter Quantity: 3

    =======================

    ==-=-=Flower Shop=-=-==

    -----------------------

    Flower Type: Daisies

    Flower Color: Various

    Arrangement: Bouquet

    Price: $45.50

    Quantity: 3

    Total Price: $136.50

    =======================

    Press any key to continue . . .

  18. Close the DOS window