defining new data types in c++

Upload: stephy-withlotsoflove

Post on 03-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Defining New Data Types in c++

    1/33

    Defining new data types in C++

    Part 1: enums & structs

  • 7/29/2019 Defining New Data Types in c++

    2/33

    Enumerated types

    An enumeration is a data type in which labels for

    all possible values of the type can be listed

    The type declaration consists of the keywordenumfollowed by the name of the new type and a

    block of code in which labels for all values of the

    type are listed

    Syntax:

    enum NewTypeName {value1, value2, , valueN};

  • 7/29/2019 Defining New Data Types in c++

    3/33

    Enumeration constants

    The value labels listed in an enumeration arecalled enumeration constants

    Enumeration constants must be valid C++

    identifiers; they are not string or char literals Enumeration constants are stored in memory as

    integers; by default, the first is assigned the value0, the second 1, etc.

    Thus the order of the listing determines therelative magnitude of enumeration constantvalues; the first is less than the second, which isless than the third, and so forth

  • 7/29/2019 Defining New Data Types in c++

    4/33

    Specifying different values in

    enumerations By default, the first enumeration constant

    has the value 0, the second 1, the third 2,

    etc. The default behavior can be overridden by

    assigning explicit values to one or more ofthe constants

    The next several examples illustrate thisoption

  • 7/29/2019 Defining New Data Types in c++

    5/33

    Example 1 (enum)

    The following enumeration uses explicit

    assignment to specify values for the

    symbols used in the Roman numeralsystem:

    enum RomanNum { I = 1, V = 5, X = 10, L = 50,

    C = 100, D = 500, M = 1000};

  • 7/29/2019 Defining New Data Types in c++

    6/33

    Example 2 (enum)

    The following enumeration type creates constants

    that stand for the months of the year:

    enum MonthType {JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV, DEC};

    Only the first constants value is specified; since it

    is 1, the second is 2, the third is 3, and so on until

    the last (DEC) with the value 12

  • 7/29/2019 Defining New Data Types in c++

    7/33

    Using enumerated types

    Enumerations only create new data types; toactually store and use values of the the new types,you must declare variables

    Variables of each enum type can hold only thosevalues specified by the enumeration

    For example, with the MonthType enumeration,you could declare variables and assign them

    values like the following:MonthType thisMonth = APR;

    MonthType nextMonth = MAY;

    MonthType birthMonth = nextMonth;

  • 7/29/2019 Defining New Data Types in c++

    8/33

    Operations on enumerations

    Since enumerations are not built-in data types, only someof the most common operations can be performed usingvariables of these types

    The allowable operations include: logical comparison using the relational operators (, =, ==,!=)

    simple arithmetic (but not arithmetic/assignment operations like ++or --)

    enumerations can be parameters to, and/or return values from,

    functions enumerations can be used as switch expressions and/or case labels

    in switchesexample on next slide

  • 7/29/2019 Defining New Data Types in c++

    9/33

    MonthType thisMonth;

    switch ( thisMonth ) // using enum type switch expression

    { case JAN :

    case FEB :

    case MAR : cout

  • 7/29/2019 Defining New Data Types in c++

    10/33

    Incrementing enum variables using

    type cast mechanism The operators ++ and -- are not available for use

    with enum-type variables, as previously noted

    However, enum-type variables can appear inmixed-type expressions with, for example,

    integers

    This provides a mechanism for

    increment/decrement of enumeration type

    variables

  • 7/29/2019 Defining New Data Types in c++

    11/33

    Using enum type Control

    Variable with for LoopMonthType month ;

    for (month = JAN ; month

  • 7/29/2019 Defining New Data Types in c++

    12/33

    Simple arithmetic with enumeration

    constants Previously, we defined an enumeration of

    the symbols used in the Roman numeral

    system

    We will use this enumeration to illustrate

    arithmetic with enums, and see another

    example of type casting

  • 7/29/2019 Defining New Data Types in c++

    13/33

    Example#include

    #include

    enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000};

    int main(){

    cout

  • 7/29/2019 Defining New Data Types in c++

    14/33

    Enumerated types and I/O

    The insertion ()

    operators are not defined for enum-type

    variables

    To perform input or output operations on

    user-defined types, you must provide your

    own functions

  • 7/29/2019 Defining New Data Types in c++

    15/33

    Databases

    A database is a collection of informationorganized for ease of storage and retrieval

    A library catalog is a good example of a database;such a catalog contains information about eachbook in the librarys collection

    Although each book is unique, books share

    common characteristics, such as author, title,publisher, etc.

    We store information in the database based onthese common characteristics

  • 7/29/2019 Defining New Data Types in c++

    16/33

    Database components

    At the macroscopic level, a database consists of one ormore filescontaining information

    The information in the files is stored in the form of

    records; in our example, each record would contain all ofthe information concerning a specific book Within the records, individual data items are stored in

    fields; for library books, each record would have separatefields for author, title, publisher, etc.

    All the records contain the same set of fields; they differ inthe actual data stored in the fields

  • 7/29/2019 Defining New Data Types in c++

    17/33

    Record structures

    If we wanted to create our own library database, we wouldwant to consider how people use books, and whatinformation they might want to look up

    We could come up with a preliminary list of fields toinclude, such as: Author

    Title

    Subject(s)

    Call number (the Dewey Decimal or Library of Congressclassification that determines where the book is shelved)

    ISBN (for those who delight in reading bar codes

    and many more, but this is enough to start with

  • 7/29/2019 Defining New Data Types in c++

    18/33

    Record structures in C++

    The C++ mechanism for creating a recorddata type is the struct

    A struct consists of a block of codecontaining list ofmember variabledeclarations

    The member variables represent the fieldswhere data can be stored when variables ofthe struct type are declared

  • 7/29/2019 Defining New Data Types in c++

    19/33

    Syntax for struct declarationstruct StructureName

    {

    dataType field1;

    dataType field2;

    .

    .

    .

    dataType fieldn;

    };

    StructureName must be a

    valid identifier

    Member variable declaration

    looks the same as any other

    variable declaration but the

    struct declaration, including

    declaration of member

    variables, doesnt allocateany memory must declare

    variables of the new type to

    allocate memory

  • 7/29/2019 Defining New Data Types in c++

    20/33

    Example

    struct BookRecord

    {

    string title;string author;

    string subject1, subject2, subject3;

    string callNo;

    string ISBN;

    };

  • 7/29/2019 Defining New Data Types in c++

    21/33

    Storing information in records

    A struct declaration, like the previous example,just provides a blueprint for a recordit doesntallocate memory, so there isnt anyplace to storedata

    To create an actual record, we need to declare avariable of the struct type; example:

    BookType myBook, yourBook;

    This statement allocates memory for twoBookType records; the next step is to assignvalues to these variables

  • 7/29/2019 Defining New Data Types in c++

    22/33

    Assigning data to struct variables

    In order to assign data to a struct variable, we

    must first access the individual member variables

    We do this by using the member-selectionoperator, or dot operator

    This is the same operator we use to call member

    functions, and for good reason: in both instances,

    we are accessing a member of a larger structure in

    order to perform some operation

  • 7/29/2019 Defining New Data Types in c++

    23/33

    Example

    myBook.title = Seabiscuit;myBook.author = Hillenbrand, Laura;

    myBook.subject1 = Horse racing;

    myBook.subject2 = Great Depression 1929-1939, U.S.;

    myBook.subject3 = Biscuits, Aquatic;

    myBook.ISBN = 0-345-46508-3;

    myBook.callNo = 939.41 H42;

    yourBook.title = Geeks;

    yourBook.author = Katz, Jon;

    yourBook.subject1 = Computer technicians U.S.case studies;

    yourBook.subject2 = Electronic data processing personnel U.S.case studies;yourBook.ISBN = 0-375-50298-X;

    yourBook.callNo = TK7885.54 K38;

  • 7/29/2019 Defining New Data Types in c++

    24/33

    Memory allocation and structs

    Memory for struct-type is allocated when avariable is declared

    Each struct variable contains all of themember variables listed in the structdeclaration

    You can think of a struct variable as a singlebox with several compartments, each ofwhich can contain a data item

  • 7/29/2019 Defining New Data Types in c++

    25/33

    Operations on struct variables

    The operations that can be performed on

    individual member of a struct variable depend on

    the members data type For example, all of the following statements are

    valid for a BookType variable:

    getline(cin, myBook.title);

    cout

  • 7/29/2019 Defining New Data Types in c++

    26/33

    Aggregate operations

    An aggregate operation is an operation performed on anentire struct variable (as opposed to one of its membervariables)

    The following are allowable aggregate operations on structvariables: assignment to another struct variable of the same type (example:

    yourBook = myBook;)

    pass to a function as an argument (either by value or by reference)

    use as return value from a function

    On the other hand, the following aggregate operations areNOT allowed: I/O, arithmetic, logical comparison

  • 7/29/2019 Defining New Data Types in c++

    27/33

    Notes on structs as parameters

    As previously mentioned, we can pass a struct

    variable as a value parameter

    Although this operation is permitted, it is costly:pass by value requires copying original argument to

    new memory location

    struct variables are rather large objects to copy

    It is therefore much more common to pass structvariables by reference, because then only a single

    copy of the large object is held in memory

  • 7/29/2019 Defining New Data Types in c++

    28/33

    A third way: const reference

    parameters The advantage of pass by value is the guarantee

    that an arguments value will not be changed by

    the action of a function Passing by reference could lend itself to side

    effects

    Fortunately, there is an alternative that combines

    the advantages of passing by value and passing by

    reference: passing by const reference

  • 7/29/2019 Defining New Data Types in c++

    29/33

    Using const reference parameters

    To pass by const reference, label your parameter with theampersand (&), as usual, but add the keyword const beforethe parameters data type

    For example, suppose you had a function for checking outbooks that took a BookType variable as its argument; thisfunction could take either a value of const reference

    parameter:

    void checkout (BookType b); // value parameter; must

    // copy whole object

    void checkout (BookType &b); // const ref parameter;

    // uses original memory,

    // but doesnt change it

  • 7/29/2019 Defining New Data Types in c++

    30/33

    Hierarchical structures

    A struct can contain an enum type as one of

    its member variables

    It is also possible for a struct to contain amember variable of a struct type

    Such an arrangement makes possible a

    greater level of detail in each record

  • 7/29/2019 Defining New Data Types in c++

    31/33

    31

    Example: struct MachineRec Information about each machine in a shop

    contains:

    an idNumber,

    a written description,

    the purchase date,

    the cost,

    and a history (including failure rate, number of

    days down, and date of last service).

  • 7/29/2019 Defining New Data Types in c++

    32/33

    32

    struct DateType

    { int month ; // Assume 1 . . 12

    int day ; // Assume 1 . . 31

    int year ; // Assume 1900 . . 2050

    };

    struct StatisticsType

    { float failRate ;

    DateType lastServiced ; // DateType is a struct type

    int downDays ;} ;

    struct MachineRec

    { int idNumber ;

    string description ;

    StatisticsType history ; // StatisticsType is a struct type

    DateType purchaseDate ;

    float cost ;

    } ;

  • 7/29/2019 Defining New Data Types in c++

    33/33

    33

    struct type variable machine

    7000

    .idNumber .description . history .purchaseDate .cost

    .month .day .year

    5719 DRILLING 3 21 1995 8000.0

    .failrate .lastServiced .downdays

    .02 1 25 1999 4.month .day .year

    machine.history.lastServiced.year has value 1999