Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Similar documents
Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Chapter 5 Functions. Introducing Functions

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Answers to Review Questions Chapter 7

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Appendix K Introduction to Microsoft Visual C++ 6.0

Comp151. Definitions & Declarations

A Summary of Operator Overloading

EP241 Computer Programming

Chapter One Introduction to Programming

Object Oriented Software Design II

Moving from C++ to VBA

Computer Programming C++ Classes and Objects 15 th Lecture

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ INTERVIEW QUESTIONS

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Phasors. Phasors. by Prof. Dr. Osman SEVAİOĞLU Electrical and Electronics Engineering Department. ^ V cos (wt + θ) ^ V sin (wt + θ)

An Incomplete C++ Primer. University of Wyoming MA 5310

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

2 Session Two - Complex Numbers and Vectors

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

7.7 Case Study: Calculating Depreciation

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

C++ Programming Language

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Passing 1D arrays to functions.

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Member Functions of the istream Class

Data Structures using OOP C++ Lecture 1

Mathematics. ( : Focus on free Education) (Chapter 5) (Complex Numbers and Quadratic Equations) (Class XI)

The Method of Partial Fractions Math 121 Calculus II Spring 2015

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Introduction to Object-Oriented Programming in MATLAB

MATLAB Workshop 3 - Vectors in MATLAB

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

CISC 181 Project 3 Designing Classes for Bank Accounts

Ch 7-1. Object-Oriented Programming and Classes

Sequential Program Execution

Functional Programming in C++11

9.4. The Scalar Product. Introduction. Prerequisites. Learning Style. Learning Outcomes

Week 13 Trigonometric Form of Complex Numbers

Georgia Department of Education Kathy Cox, State Superintendent of Schools 7/19/2005 All Rights Reserved 1

The While Loop. Objectives. Textbook. WHILE Loops

C Programming Language

13 Classes & Objects with Constructors/Destructors

COMPUTER SCIENCE 1999 (Delhi Board)

ALGEBRA 2/TRIGONOMETRY

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

F ahrenheit = 9 Celsius + 32

Common Beginner C++ Programming Mistakes

Solving Problems Recursively

C++ Language Tutorial

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

The Vector or Cross Product

C++FA 5.1 PRACTICE MID-TERM EXAM

CSI33 Data Structures

3. KINEMATICS IN TWO DIMENSIONS; VECTORS.

MAC Learning Objectives. Module 10. Polar Form of Complex Numbers. There are two major topics in this module:

Function Overloading I

C++ Input/Output: Streams

ALGEBRA 2/TRIGONOMETRY

Introduction to Complex Numbers in Physics/Engineering

Trigonometry Hard Problems

Conditions & Boolean Expressions

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Note: Syntactically, a ; is needed at the end of a struct definition.

COSC 181 Foundations of Computer Programming. Class 6

Expense Management. Configuration and Use of the Expense Management Module of Xpert.NET

THE COMPLEX EXPONENTIAL FUNCTION

Introduction to Programming Block Tutorial C/C++

Transmission Lines. Smith Chart

Basics of I/O Streams and File I/O

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

It has a parameter list Account(String n, double b) in the creation of an instance of this class.

Beginner s Matlab Tutorial

C++ Crash Kurs. C++ Object-Oriented Programming

ALGEBRA 2/TRIGONOMETRY

5 Arrays and Pointers

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

I PUC - Computer Science. Practical s Syllabus. Contents

Appendix M: Introduction to Microsoft Visual C Express Edition

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Formatting Numbers with C++ Output Streams

Vectors VECTOR PRODUCT. Graham S McDonald. A Tutorial Module for learning about the vector product of two vectors. Table of contents Begin Tutorial

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

ALGORITHMS AND FLOWCHARTS

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Compiler Construction

Lecture 14: Section 3.3

Curriculum Map. Discipline: Computer Science Course: C++

Transcription:

Classes May -7, 005 Schedule Structures and Classes in C++ Larry Caretto Computer Science 06 Computing in Engineering and Science May and 7, 005 Today and Tuesday: Lecture on classes Thursday (May 9) Project deadline Review for final Tuesday, May 4: Final exam :45 to :45 pm in this room Friday, May 7: Last day for late assignments Outline Introduction to C/C++ structured variables (structs) Expansion of structs to classes Classes versus objects of a class Example of a class to be used for calculations with complex numbers Definition of class Use of class Details of class functions Goals for This Topic Provide introduction to structs and classes used in object-oriented programming Show how functions similar to those we have used for input/output (e.g.,.good(),.open(), etc.) are written Give background appropriate for students interested in further study of C++ Individuals working on programs that use structs and classes Topics will not be covered on final What is a Structure? Previously, we have used simple variables and arrays Arrays as example of a data structure x is array x[i] is array element all elements must have the same type What if we want a structure to represent data for each student at CSUN We would want several pieces of information, name, ID, etc. with different data types Another Example of a Structure In exercise eight we had data on x and y for which we wanted to compute the count, mean, standard deviation, max and min We could declare a structure to hold the data and the values to be computed. We would then declare different variables as having the type named by the struct Each struct variable has each component defined in the structure

Classes May -7, 005 Definition of a Structure struct DataSet double data[max_data]; // all data // values int count; // number of values double mean; // mean value double max; // maximum value double min; // minimum value double stddev;// standard deviation ; // note ; at end DataSet is name of struct (like a type) Use of a Structure DataSet x, y, xlow, ylow, xhigh, yhigh; // declare variables getinput ( x.data, x.count ) getinput ( y.data, y.count ) x.mean = getaverage( x.data, x.count ) Each variable has all the fields defined in the structure Refer to values as <variable>.<field> Can pass entire structures to functions Note that struct DataSet is abstract concept until variables with that struct are created From structs to classes Classes are similar to structs Abstract data type that defines a structure Variables are declared that belong to a class In addition to having data values, classes can have functions that operate on data Can hide data from user in classes User cannot change data by accident User can only access data through functions Use can change data in ways allowed by functions for the class Class Definition and Use Class declaration Specify data and functions as public or private Declares data items belonging to class Provides prototypes of class member functions and friend functions May have function body declared as inline functions Only member functions can access private member Definition of class member functions Separate from class declaration Usually done in separate file File Structure Header file Contains class declaration (with member function prototypes) Used in files that define member functions and files that use member functions Definition of class member functions in separate file Other files that use classes include header file with class definitions Complex Number Class Shows example of class that allows operations on complex numbers Usually seen in electrical circuits, aerodynamics, and electromagnetics Complex numbers have a real and an imaginary part We want to be able to perform mathematical operations with complex numbers Also need input/output

Classes May -7, 005 Complex Number, Two basic representations Rectangular: real (x) and imaginary (y) parts Polar: magnitude (r) and angle (θ) jθ = x + jy = re j = x = r cos( θ ) r = x + y y = r sin( θ ) θ = tan y x Complex Number Operations = c x = cx y = cy = ± x = x ± x y = y ± y = = x y ( x + y ) ( x + y ) = xx y y = y x + y x x = xx + y y y = y x y x Complex class Class declaration Two member data components: real and imaginary parts of a complex number Various member functions to get data about the complex number, provide input and output and define operators for complex numbers Complex class objects are complex numbers Functions specified in class declaration implemented in separate (header) file Start with class declaration that will show prototypes of available functions/operators In file complex.h used by other functions Show main function that uses the complex class show commands and output from the commands Show definition of member functions after showing prototypes and result of use All files have header, complex.h class complex private: double Re; double Im; // Real part of complex number // Imaginary part of complex number // Various function operators. Note overloading and friends. // Member functions (only prototypes required in class // definition. These are public so that they can be used // by remainder of code. Some are inline. public: complex() Re = 0; Im = 0; // constructor complex( double inre, double inim ) // second constuctor Re = inre; Im = inim; double getre() return Re; // returns value double getim() return Im; // returns value double getmagnitude() return sqrt( Re * Re + Im * Im ); // magnitude of number double getphase() // phase angle return atan( Im, Re ); friend ostream& operator<< ( ostream& os, const complex& c ) os << '(' << c.re << ", " << c.im << ')'; return os; friend istream& operator>> ( istream& is, complex& c ) is >> c.re >> c.im; return is; complex plus( complex c ); friend complex add( complex c, complex c ); complex operator+( complex c ); complex operator*( complex c ); friend complex operator*( complex c, double d ); friend complex operator*( double d, complex c ); ; // End of class definition uses a plus a semicolon!

Classes May -7, 005 Members and prototypes provided in class declaration tell us what is available If we understand what the functions are supposed to do, we can use them without knowing their details The following charts show a main function that declares and uses complex objects Output shown as comments in the code to see results of class functions Note: + 4 = 5 and tan(4/5) = 5.0 o // main shows use of the complex class #include complex.h DEGREES_PER_RADIAN = 45 / atan(); // global constant int main() // Declare and output complex data types. complex a; // same as complex a( 0, 0 ) complex b(, 4 ); // Re = and Im = 4 cout << "a = " << a << " and b = " << b << endl; cout << "The magnitude of b is: " << b.getmagnitude() << endl; cout << "The phase angle of b is: " << ( b.getphase() * DEGREES_PER_RADIAN ) << " degrees.\n"; a = (0, 0) and b = (, 4) The magnitude of b is: 5 The phase angle of b is: 5.0 degrees. */ // Show output operator and addition operations complex c( 7, 0 ); cout << "\nc = " << c << endl; cout << "Use of add function, add( b, c ) = " << add( b, c ); cout << "Use of + operator, b + c = " << ( b + c ) << endl; cout << "Before b.plus( c ), b = " << b; cout << " and b.plus( c ) = " << b.plus( c ) << endl; cout << "After b.plus( c ), b = " << b << endl; // Show multiplication operations c = (7, 0) Use of add function, add( b, c ) = (0, 4) Use of + operator, b + c = (0, 4) Before b.plus( c ), b = (, 4) and b.plus( c ) = (0, 4) After b.plus( c ), b = (0, 4) // Show multiplication operations cout << "\n * b = " << ( * b ) << " and b * = " << ( b * ) << endl; complex d = c * b; cout << "The real part of d is: " << d.getre() << endl; cout << "The imaginary part of d is: " << d.getim() << endl; cout << "The magnitude of d is: " << d.getmagnitude() << endl; cout << "The phase angle of d is: " << d.getphase() << " radians.\n"; // Test overloaded extraction (>>) operator for input * b = (0, 8) and b * = (0, 8) The real part of d is: 74 The imaginary part of d is: 94 The magnitude of d is: 9.6 The phase angle of d is: 0.90888 radians. // Test overloaded extraction (>>) operator for input cout << "\nenter real and imaginary parts of your number: "; cin >> a; cout << "The complex number you entered is: " << a << endl; return EXIT_SUCCESS; Enter the real and imaginary parts of your number: 5 0 The complex number you entered is: (5, 0) Press any key to continue Now examine details of class functions Function code similar to normal functions Have special code for operators Use complex:: before names of functions Use header complex.h with class definitions in implementation code file Use of special meanings for operators in classes is called operator overloading 4

Classes May -7, 005 // Actual function definitions go here // All functions declared in class (but not written as // inline functions) are defined below. // See http://mathworld.wolfram.com/complexnumber.html // for background on formulae used in these functions complex complex::plus( complex c ) // The command b.plus( c ) increases the value // of the complex number, b, by the input value c. Re = Re + c.re; // Re used without an object refers Im = Im + c.im; // to object used in call b.plus(c) return *this; // Method for returning operations on // base complex number, b complex add( complex c, complex c ) complex c; c.re = c.re + c.re; // Add two complex numbers and c.im = c.im + c.im; // return the result. Use: return c; // complex = add( a, b ); complex complex::operator+( complex c ) // Add two complex numbers by usual addition // operator. Use in code: complex u, v, w; // w = u + v; // Adds u and v; result in w complex c; c.re = Re + c.re; c.im = Im + c.im; return c; complex complex::operator*( complex c ) // Multiply two complex numbers by usual // operator. Use in code: complex u, v, w; // w = u * v; // Multiply u and v; result in w complex c; c.re = Re * c.re - Im + c.im; c.im = Re * c.re + Im + c.im; return c; complex operator*( complex c, double d ) // Multiply a complex number by scalar. // Used when scalar follows the = sign complex c; c.re = d * c.re; c.im = d * c.im; return c; complex operator*( double d, complex c ) // Multiply a complex number by scalar. // Used when scalar follows the = sign complex c; c.re = d * c.re; c.im = d * c.im; return c; Conclusions structs and classes provide powerful tools for implementing problems Can simplify code and provide natural mathematical language for user C++ has a standard template library (STL) for many common structures, e.g. vectors, complex numbers, and strings Can use library functions without being concerned about their internal structure 5