cps120: introduction to computer science lecture 16 data structures, oop & advanced strings

Post on 18-Jan-2018

231 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Using Pointers Pointers must be initialized e.g. iptr =&I; This reads iptr is assigned the address of i

TRANSCRIPT

CPS120: Introduction to Computer Science

Lecture 16Data Structures, OOP &

Advanced Strings

Pointer Use in C++.

A pointer is a variable or constant that holds a memory address

a) Hexadecimal numbers are used for representing memory locations

216793216794 216801 iptr…216801 3 i216802

Using Pointers

Pointers must be initializede.g. iptr =&I;

This reads iptr is assigned the address of i

Intializing Pointers

Declare pointers before use, as with other variables. Each variable being declared as a pointer must be preceded by an asterisk (*). Initialize pointers before use to a 0, NULL or an address to prevent unexpected results

Pointer Operators

& is the address operator which returns the address of its operand * is the indirection operator or dereferencing operator and returns the value to which the operand (pointer) points. sizeof - used to determine the size of an array during program compiliation

Using enum

enum allows you to create your own simple data types for special purposes

Create a typeGive it a nameSpecify values that are acceptable

enum sizes {small, medium, large, jumbo};The compiler assigns an integer to each enum item

typedef

typedef gives a new name to an existing data type

typedef float real;

Confusing to the reader, should be used sparingly

StructuresStructures group variables together in order to make one's programming task more efficient.

Any combination of variables can be combined into one structure. This is a useful and efficient way to store data.

struct Student { string socSecNum; string lastName; string firstName; int pointsEarned; double gpa; };

Using Structures

Each of the different variables are called members of the structure

Structures allow us to keep related data referring to individual members together

Strings, integer, and floating-point variables may be grouped together into one structure.

In effect, we have created our own customized data type.

The semicolon after the closing curly brace is required

Using the new data structure

The structure definition should be placed above the main function of a program but below the compiler directives Declare an actual variable of this programmer-created data type within a function (such as main) in order to make use of this structureDone with a declaration statement likeStudent freshmen;This reates a variable called freshmen of the data type Student

Assigning values to the structure

To assign a grade point average (GPA) of 3.4 to the gpa member of the variable freshmen, use the statement:

freshmen.gpa = 3.4; The period (.) that is used between the variable name freshmen and the member gpa is called the dot operator.

The dot operator simply us to reference individual members of a structure

Nested StructuresYou can use a previously defined structure as a member of another structureAddress is nested inside of the Customer structure. Since Address is used within Customer, the structure definition for Address must be placed above Customer in order to avoid compile errors struct Address{ string street; string city; string state; int zip;}; struct Customer{ string name; string phone; Address homeAddress; Address businessAddress; };

CPS120: Introduction to Computer Science

Lecture 16BObject-Oriented Concepts

The Procedural Paradigm

The functions and algorithms are the focus, with data viewed as something for the functions to manipulate

Object-Oriented Paradigm

Data should be placed inside the objects and that these objects should communicate with each other in the form of messages

Classes

The definition of an object is know as a classIt is similar to using basic data structures in C++

When you declare an object, you are said to have instantiated it (given it instances)Objects are members of a class

Paul Millis, George Bush and George Washington being members of the human being class

The design of a class is as important as its implementation

Including Classes in C++

For classes, the #include directive uses different punctuation for header (.h) files

Quotation marks are used when the header file is a source file in the same location as the program source codeAngle brackets are used when the header file is one of the compiler's pre-compiled library functions

Designing a Class

Think in an object-oriented wayE.g. an answering machine encapsulates the functions of an answering machine with the data (messages).

The buttons are the equivalent of sending messages to the machine

Defining a Class

Functions and variables that are prototyped and declared in a class definition are called members

Public vs Private

Private: Cannot be accessed outside the objectPublic: Can have access to all the variables and functions

public: // constructors circle(); // default constructor circle(const circle &); // copy constructor // member functions void SetRadius(float); double Area();

private: // data float radius;

Constructors

Allow all data encapsulated within an object to be initialized to preset values so that errors can be avoided

Member Functions

Provide a way for a programmer to pass data to and get data from an objectImplemented like a normal C++ function

Except -- The class name and the scope-resolution operator (: :) precede the function name

circle : : circle() // default constructor

OOP Advantages: Reusability

Reusability is a major benefit of object-oriented programming

OOP Advantages: Containment

Containment is a term used to describe an object that contains one or more objects as members

(Passes the 'has-a' rule)

OOP Advantages: Inheritance

Inheritance is the term used to describe an object that inherits properties from another object

(Passes the 'is-a' rule) The class from which an object inherits properties is called a parent class or base classThe class that inherits the properties is called a child class or derived class

CPS120: Introduction to Computer Science

Lecture 16CAdvanced Strings

Library functions manipulate strings

length functionstringLength = userString.length( );To compare two stringsif (string1 = = string2)Test two strings alphabetically if (string1 < string2){ cout << "string1 comes before string2

alphabetically ";}

Library functions manipulate strings

To compare two stringsif (string1 = = string2)

Library functions manipulate strings

Test two strings alphabetically if (string1 < string2){ cout << "string1 comes before

string2 alphabetically ";

}

Concatenation To combine two strings into one larger string:

name = "John";lastName = "Doe";cout << name + lastName;

The character array that is going to receive the additional characters must have enough memory allocated to hold the additional charactersThe STRCAT function will continue to add characters even if it reaches the end of the destination character array

The result is that other memory is overwrittenwith the remaining string data.

A String Class

A string class can make C++ strings much easier to usea) A string class can provide bounds checking to avoid string errorsb) A string class can also allow the use of standard C++ operators when working with stringsi) +, =, and = =

Converting Strings

There are C++ library functions that allow you to convert numbers stored in strings to integer and floating point values

atoi-- numbers stored as characters can be converted for calculationsatol -- converts a string to a long integeratof -- convers a string to a floating point number

Using A String Class

Required header file#include "oostring.h"

Instantiating a String Object

// Instantiate empty string objectoostring MyString1;

// Initialize while instantiating oostring MyString2("Hello, World!");

Assigning Values to Strings

MyString1 = MyString2;MyString1 = "string variable";MyString1 = 'A';

top related