第三章习题答案 // include definition of class GradeBook from GradeBook.h #include "GradeBook.h"
|
|
- Cora Boone
- 5 years ago
- Views:
Transcription
1 第三章习题答案 3.11 // Exercise 3.11 Solution: GradeBook.h // Definition of GradeBook class that stores an instructor's name. #include <string> // program uses C++ standard string class using std::string; // GradeBook class definition class GradeBook public: // constructor initializes course name and instructor name GradeBook( string, string ); void setcoursename( string ); // function to set the course name string getcoursename(); // function to retrieve the course name void setinstructorname( string ); // function to set instructor name string getinstructorname(); // function to retrieve instructor name void displaymessage(); // display welcome message and instructor name private: string coursename; // course name for this GradeBook string instructorname; // instructor name for this GradeBook }; // end class GradeBook // Exercise 3.11 Solution: GradeBook.cpp // Member-function definitions for class GradeBook. // include definition of class GradeBook from GradeBook.h #include "GradeBook.h" // constructor initializes coursename and instructorname // with strings supplied as arguments GradeBook::GradeBook( string course, string instructor ) setcoursename( course ); // initializes coursename setinstructorname( instructor ); // initializes instructorname } // end GradeBook constructor // function to set the course name
2 void GradeBook::setCourseName( string name ) coursename = name; // store the course name } // end function setcoursename // function to retrieve the course name string GradeBook::getCourseName() return coursename; } // end function getcoursename // function to set the instructor name void GradeBook::setInstructorName( string name ) instructorname = name; // store the instructor name } // end function setinstructorname // function to retrieve the instructor name string GradeBook::getInstructorName() return instructorname; } // end function getinstructorname // display a welcome message and the instructor's name void GradeBook::displayMessage() // display a welcome message containing the course name cout << "Welcome to the grade book for\n" << getcoursename() << "!" << endl; // display the instructor's name cout << "This course is presented by: " << getinstructorname() << endl; } // end function displaymessage // Exercise 3.11 Solution: ex03_11.cpp // Test program for modified GradeBook class. // include definition of class GradeBook from GradeBook.h #include "GradeBook.h" // function main begins program execution
3 int main() // create a GradeBook object; pass a course name and instructor name GradeBook gradebook( "CS101 Introduction to C++ Programming", "Professor Smith" ); // display initial value of instructorname of GradeBook object cout << "gradebook instructor name is: " << gradebook.getinstructorname() << "\n\n"; // modify the instructorname using set function gradebook.setinstructorname( "Assistant Professor Bates" ); // display new value of instructorname cout << "new gradebook instructor name is: " << gradebook.getinstructorname() << "\n\n"; // display welcome message and instructor's name gradebook.displaymessage(); return 0; // indicate successful termination } // end main 3.13 // Exercise 3.13 Solution: Invoice.h // Definition of Invoice class that represents an invoice // for an item sold at a hardware store. #include <string> // program uses C++ standard string class using std::string; // Invoice class definition class Invoice public: // constructor initializes the four data members Invoice( string, string, int, int ); // set and get functions for the four data members void setpartnumber( string ); // part number string getpartnumber(); void setpartdescription( string ); // part description string getpartdescription(); void setquantity( int ); // quantity int getquantity();
4 void setpriceperitem( int ); // price per item int getpriceperitem(); // calculates invoice amount by multiplying quantity x price per item int getinvoiceamount(); private: string partnumber; // the number of the part being sold string partdescription; // description of the part being sold int quantity; // how many of the items are being sold int priceperitem; // price per item }; // end class Invoice // Exercise 3.13 Solution: Invoice.cpp // Member-function definitions for class Invoice. // include definition of class Invoice from Invoice.h #include "Invoice.h" // Invoice constructor initializes the class's four data members Invoice::Invoice( string number, string description, int count, int price ) setpartnumber( number ); // store partnumber setpartdescription( description ); // store partdescription setquantity( count ); // validate and store quantity setpriceperitem( price ); // validate and store priceperitem } // end Invoice constructor // set part number void Invoice::setPartNumber( string number ) partnumber = number; // no validation needed } // end function setpartnumber // get part number string Invoice::getPartNumber() return partnumber; } // end function getpartnumber
5 // set part description void Invoice::setPartDescription( string description ) partdescription = description; // no validation needed } // end function setpartdescription // get part description string Invoice::getPartDescription() return partdescription; } // end function getpartdescription // set quantity; if not positive, set to 0 void Invoice::setQuantity( int count ) if ( count > 0 ) // if quantity is positive quantity = count; // set quantity to count if ( count <= 0 ) // if quantity is not positive quantity = 0; // set quantity to 0 cout << "\nquantity cannot be negative. quantity set to 0.\n"; } // end if } // end function setquantity // get quantity int Invoice::getQuantity() return quantity; } // end function getquantity // set price per item; if not positive, set to 0 void Invoice::setPricePerItem( int price ) if ( price > 0 ) // if price is positive priceperitem = price; // set priceperitem to price if ( price <= 0 ) // if price is not positive priceperitem = 0; // set priceperitem to 0 cout << "\npriceperitem cannot be negative. " << "priceperitem set to 0.\n"; } // end if } // end function setpriceperitem
6 // get price per item int Invoice::getPricePerItem() return priceperitem; } // end function getpriceperitem // calulates invoice amount by multiplying quantity x price per item int Invoice::getInvoiceAmount() return getquantity() * getpriceperitem(); } // end function getinvoiceamount // Exercise 3.13 Solution: ex03_13.cpp // Create and manipulate an Invoice object. using std::cin; // include definition of class Invoice from Invoice.h #include "Invoice.h" // function main begins program execution int main() // create an Invoice object Invoice invoice( "12345", "Hammer", 100, 5 ); // display the invoice data members and calculate the amount cout << "Part number: " << invoice.getpartnumber() << endl; cout << "Part description: " << invoice.getpartdescription() << endl; cout << "Quantity: " << invoice.getquantity() << endl; cout << "Price per item: $" << invoice.getpriceperitem() << endl; cout << "Invoice amount: $" << invoice.getinvoiceamount() << endl; // modify the invoice data members invoice.setpartnumber( "123456" ); invoice.setpartdescription( "Saw" ); invoice.setquantity( -5 ); // negative quantity, so quantity set to 0 invoice.setpriceperitem( 10 ); cout << "\ninvoice data members modified.\n\n"; // display the modified invoice data members and calculate new amount
7 cout << "Part number: " << invoice.getpartnumber() << endl; cout << "Part description: " << invoice.getpartdescription() << endl; cout << "Quantity: " << invoice.getquantity() << endl; cout << "Price per item: $" << invoice.getpriceperitem() << endl; cout << "Invoice amount: $" << invoice.getinvoiceamount() << endl; return 0; // indicate successful termination } // end main 3.14 // Exercise 3.14 Solution: Employee.h // Employee class definition. #include <string> // program uses C++ standard string class using std::string; // Employee class definition class Employee public: Employee( string, string, int ); // constructor sets data members void setfirstname( string ); // set first name string getfirstname(); // return first name void setlastname( string ); // set last name string getlastname(); // return last name void setmonthlysalary( int ); // set weekly salary int getmonthlysalary(); // return weekly salary private: string firstname; // Employee's first name string lastname; // Employee's last name int monthlysalary; // Employee's salary per month }; // end class Employee // Exercise 3.14 Solution: Employee.cpp // Employee class member-function definitions. #include "Employee.h" // Employee class definition // Employee constructor initializes the three data members Employee::Employee( string first, string last, int salary )
8 setfirstname( first ); // store first name setlastname( last ); // store last name setmonthlysalary( salary ); // validate and store monthly salary } // end Employee constructor // set first name void Employee::setFirstName( string name ) firstname = name; // no validation needed } // end function setfirstname // return first name string Employee::getFirstName() return firstname; } // end function getfirstname // set last name void Employee::setLastName( string name ) lastname = name; // no validation needed } // end function setlastname // return last name string Employee::getLastName() return lastname; } // end function getlastname // set monthly salary; if not positive, set to 0.0 void Employee::setMonthlySalary( int salary ) if ( salary > 0 ) // if salary is positive monthlysalary = salary; // set monthlysalary to salary if ( salary <= 0 ) // if salary is not positive monthlysalary = 0; // set monthlysalary to 0.0 } // end function setmonthlysalary // return monthly salary int Employee::getMonthlySalary() return monthlysalary;
9 } // end function getmonthlysalary // Exercise 3.14 Solution: ex03_14.cpp // Create and manipulate two Employee objects. #include "Employee.h" // include definition of class Employee // function main begins program execution int main() // create two Employee objects Employee employee1( "Lisa", "Roberts", 4500 ); Employee employee2( "Mark", "Stein", 4000 ); // display each Employee's yearly salary cout << "Employees' yearly salaries: " << endl; // retrieve and display employee1's monthly salary multiplied by 12 int monthlysalary1 = employee1.getmonthlysalary(); cout << employee1.getfirstname() << " " << employee1.getlastname() << ": $" << monthlysalary1 * 12 << endl; // retrieve and display employee2's monthly salary multiplied by 12 int monthlysalary2 = employee2.getmonthlysalary(); cout << employee2.getfirstname() << " " << employee2.getlastname() << ": $" << monthlysalary2 * 12 << endl; // give each Employee a 10% raise employee1.setmonthlysalary( monthlysalary1 + monthlysalary1 / 10 ); employee2.setmonthlysalary( monthlysalary2 + monthlysalary2 / 10 ); // display each Employee's yearly salary again cout << "\nemployees' yearly salaries after 10% raise: " << endl; // retrieve and display employee1's monthly salary multiplied by 12 monthlysalary1 = employee1.getmonthlysalary(); cout << employee1.getfirstname() << " " << employee1.getlastname() << ": $" << monthlysalary1 * 12 << endl; monthlysalary2 = employee2.getmonthlysalary(); cout << employee2.getfirstname() << " " << employee2.getlastname()
10 << ": $" << monthlysalary2 * 12 << endl; return 0; // indicate successful termination } // end main 3.15 // Exercise 3.15 Solution: Date.h // Definition of class Date. // class Date definition class Date public: Date( int, int, int ); // constructor initializes data members void setmonth( int ); // set month int getmonth(); // return month void setday( int ); // set day int getday(); // return day void setyear( int ); // set year int getyear(); // return year void displaydate(); // displays date in mm/dd/yyyy format private: int month; // the month of the date int day; // the day of the date int year; // the year of the date }; // end class Date // Exercise 3.15 Solution: Date.cpp // Member-function definitions for class Date. #include "Date.h" // include definition of class Date from Date.h // Date constructor that initializes the three data members; // assume values provided are correct (really should validate) Date::Date( int m, int d, int y ) setmonth( m ); setday( d ); setyear( y );
11 } // end Date constructor // set month void Date::setMonth( int m ) month = m; if ( month < 1 ) month = 1; if ( month > 12 ) month = 1; } // end function setmonth // return month int Date::getMonth() return month; } // end function getmonth // set day void Date::setDay( int d ) day = d; } // end function setday // return day int Date::getDay() return day; } // end function getday // set year void Date::setYear( int y ) year = y; } // end function setyear // return year int Date::getYear() return year; } // end function getyear
12 // print Date in the format mm/dd/yyyy void Date::displayDate() cout << month << '/' << day << '/' << year << endl; } // end function displaydate // Exercise 3.15 Solution: ex03_15.cpp // Demonstrates class Date's capabilities. #include "Date.h" // include definition of class Date from Date.h // function main begins program execution int main() Date date( 5, 6, 1981 ); // create a Date object for May 6, 1981 // display the values of the three Date data members cout << "Month: " << date.getmonth() << endl; cout << "Day: " << date.getday() << endl; cout << "Year: " << date.getyear() << endl; cout << "\noriginal date:" << endl; date.displaydate(); // output the Date as 5/6/1981 // modify the Date date.setmonth( 13 ); // invalid month date.setday( 1 ); date.setyear( 2005 ); cout << "\nnew date:" << endl; date.displaydate(); // output the modified date (1/1/2005) return 0; // indicate successful termination } // end main
13 第四章习题答案 4.27 // Exercise 4.27 Solution: Binary.h // Definition of class Binary. // Member function is defined in Binary.cpp // Binary class definition class Binary public: void converttodecimal(); // convert binary to decimal }; // end class Binary // Exercise 4.27 Solution: Binary.cpp // Member-function definitions for class Binary. using std::cin; #include "Binary.h" // include definition of class Binary // convert a binary number to a decimal number void Binary::convertToDecimal() int binary; // binary value int bit = 1; // bit positional value int decimal = 0; // decimal value // prompt for and read in a binary number cout << "Enter a binary number: "; cin >> binary; // convert to decimal equivalent while ( binary!= 0 ) decimal += binary % 10 * bit; binary /= 10; bit *= 2; } // end while loop
14 cout << "Decimal is: " << decimal << endl; } // end function converttodecimal // Exercise 4.27 Solution: ex04_27.cpp // Test program for class Binary. #include "Binary.h" // include definition of class Binary int main() Binary application; // create Binary object application.converttodecimal(); // function to convert to decimal return 0; // indicate successful termination } // end main 4.34 // Exercise 4.34 Part A Solution: Encrypt.cpp // Member-function definitions for class Encrypt. using std::cin; #include "Encrypt.h" // include definition of class Encrypt // encrypt a four-digit number void Encrypt::encrypt() int number; // original number int digit1; // first digit int digit2; // second digit int digit3; // third digit int digit4; // fourth digit int encryptednumber; // encrypted number // enter four-digit number to be encrypted cout << "Enter a four-digit number: "; cin >> number; // encrypt digit1 = ( number / ) % 10; digit2 = ( number % 1000 / ) % 10;
15 digit3 = ( number % 100 / ) % 10; digit4 = ( number % ) % 10; encryptednumber = digit1 * 10 + digit2 + digit3 * digit4 * 100; cout << "Encrypted number is " << encryptednumber << endl; } // end function encrypt // Exercise 4.34 Part B Solution: Decrypt.cpp // Member-function definitions for class Decrypt. using std::cin; #include "Decrypt.h" // include definition of class Decrypt // decrypt a number void Decrypt::decrypt() int number; // original number int digit1; // first digit int digit2; // second digit int digit3; // third digit int digit4; // fourth digit int decryptednumber; // encrypted number // enter an encrypted number to be decrypted cout << "Enter an encrypted number: "; cin >> number; // decrypt digit1 = ( number / ) % 10; digit2 = ( number % 1000 / ) % 10; digit3 = ( number % 100 / ) % 10; digit4 = ( number % ) % 10; decryptednumber = digit1 * 10 + digit2 + digit3 * digit4 * 100; cout << "Decrypted number is " << decryptednumber << endl; } // end function decrypt
16 4.35b // Exercise 4.35 Part B Solution: E.cpp // Member-function definitions for class E. using std::cin; #include "E.h" // include definition of class E from E.h // approximates the value of E void E::approximate() int number = 1; // counter int accuracy; // accuracy of estimate int factorial = 1; // value of factorial double e = 1.0; // estimate value of e // get accuracy cout << "Enter desired accuracy of e: "; cin >> accuracy; // calculate estimation while ( number < accuracy ) factorial *= number; e += 1.0 / factorial; number++; } // end while cout << "e is " << e << endl; } // end function approximate
Introduction to Classes and Objects
3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to
More informationHow to engineer a class to separate its interface from its implementation and encourage reuse.
1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How
More informationIntroduction to Classes and Objects
3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.
More informationComputer Programming C++ Classes and Objects 6 th Lecture
Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline
More informationCS141 Programming Assignment #4
CS141 Programming Assignment #4 Due Sunday, Mar 3rd. 1) Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four
More informationPage 1 of 5. *** person.cpp *** #include "person.h" #include <string> #include <iostream> using namespace std; *** person.h ***
#ifndef PERSON_H #define PERSON_H #include "date.h" *** person.h *** class Person // constructors Person( ); Person( const string &name, const int id ); Person( const string &name, const int id, const
More informationFunctions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.
1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare
More informationfinal Methods and Classes
1 2 OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods
More informationObject Oriented Programming. Java-Lecture 1
Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen
More informationHomework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions
Homework 3 Due: Feb 25, 23:59pm Section 1 (20 pts, 2 pts each) Multiple Choice Questions Q1: A function that modifies an array by using pointer arithmetic such as ++ptr to process every value of the array
More informationObject-Oriented Programming: Polymorphism Pearson Education, Inc. All rights reserved.
1 10 Object-Oriented Programming: Polymorphism 2 A Motivating Example Employee as an abstract superclass. Lots of different types of employees (well, 4). Executing the same code on all different types
More informationControl Statements: Part Pearson Education, Inc. All rights reserved.
1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is
More informationExercise 1: Class Employee: public class Employee { private String firstname; private String lastname; private double monthlysalary;
Exercise 1: Class Employee: public class Employee { private String firstname; private String lastname; private double monthlysalary; public String getfirstname() { return firstname; public void setfirstname(string
More informationWelcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.
1 Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. public class Welcome1 // main method begins execution of Java application System.out.println( "Welcome to Java Programming!" ); } //
More informationFunctions and Recursion
Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game
More informationObject Oriented Programming with C++ (24)
Object Oriented Programming with C++ (24) Zhang, Xinyu Department of Computer Science and Engineering, Ewha Womans University, Seoul, Korea zhangxy@ewha.ac.kr Polymorphism (II) Chapter 13 Outline Review
More informationAL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I
AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the
More informationAnswer ALL Questions. Each Question carries ONE Mark.
SECTION A (10 MARKS) Answer ALL Questions. Each Question carries ONE Mark. 1 (a) Choose the correct answer: (5 Marks) i. Which of the following is not a valid primitive type : a. char b. double c. int
More informationObject Oriented Design
Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use
More informationControl Statements: Part Pearson Education, Inc. All rights reserved.
1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is
More informationSolutions for H7. Lecture: Xu Ying Liu
Lecture: Xu Ying Liu 2011 0 Ex13.12 1 // Exercise 13.12 Solution: Date.h 2 // Date class definition. 3 #ifndef DATE_H 4 #define DATE_H 6 #include 7 using namespace std; 8 9 class Date 10 { 11
More informationFig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10
CHAPTER 7 CLASSES: PART II 1 Illustrations List (Main Page) Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10 Using a Time class with const objects and const member
More informationYanbu University College Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Lab Exercise 10
Yanbu University College BACHELOR OF SCIENCE IN Applied Computer Science (ACS) Introduction to Computer Science (CS 102) Third Semester Academic Year 2011 2012 Lab Exercise 10 Course Instructor: Mohammed
More informationClasses: A Deeper Look. Systems Programming
Classes: A Deeper Look Systems Programming Deeper into C++ Classes const objects and const member functions Composition Friendship this pointer Dynamic memory management new and delete operators static
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationby Pearson Education, Inc. All Rights Reserved. 2
Suppose you want to drive a car and make it go faster by pressing down on its accelerator pedal. Before you can drive a car, someone has to design it and build it. A car typically begins as engineering
More informationCIS 190: C/C++ Programming. Classes in C++
CIS 190: C/C++ Programming Classes in C++ Outline Header Protection Functions in C++ Procedural Programming vs OOP Classes Access Constructors Headers in C++ done same way as in C including user.h files:
More informationA A B U n i v e r s i t y
A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com
More informationIntroduction to Classes and Objects
1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.
More informationBasic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of
Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1 ECE 161 WEEK
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Polymorphism Lecture 8 September 28/29, 2004 Introduction 2 Polymorphism Program in the general Derived-class object can be treated as base-class object is -a
More informationClasses: A Deeper Look, Part 1
9 Classes: A Deeper Look, Part 1 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition errors caused by including more than one copy of a header file
More informationIntroduction to Classes and Objects Pearson Education, Inc. All rights reserved.
1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.
More informationAssoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down
More informationthis Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer
this Pointer, Constant Functions, Static Data Members, and Static Member Functions 3/2/07 CS250 Introduction to Computer Science II 1 this Pointer (11.1) functions - only one copy of each function exists
More informationClasses: A Deeper Look, Part 2
10 But what, to serve our private ends, Forbids the cheating of our friends? Charles Churchill Instead of this absurd division into sexes they ought to class people as static and dynamic. Evelyn Waugh
More informationIntroduction to Classes and Objects Pearson Education, Inc. All rights reserved.
1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.
More informationAngela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.
C++ Classes: Part II Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 17.2 const (Constant) Objects and
More informationComputer Programming Class Members 9 th Lecture
Computer Programming Class Members 9 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline Class
More informationFig Fig Fig. 10.3
CHAPTER 10 VIRTUAL FUNCTIONS AND POLYMORPHISM 1 Illustrations List (Main Page) Fig. 10.2 Fig. 10.3. Definition of abstract base class Shape. Flow of control of a virtual function call. CHAPTER 10 VIRTUAL
More informationOBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend
More information[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";
Page 1 of 10 [Page 177 (continued)] Exercises 4.11 Identify and correct the error(s) in each of the following: a. if ( age >= 65 ); cout
More informationLecture 7: Classes and Objects CS2301
Lecture 7: Classes and Objects NADA ALZAHRANI CS2301 1 What is OOP? Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly
More informationtypedef int Array[10]; String name; Array ages;
Morteza Noferesti The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; Length a, b, len ; Length
More informationCSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I
Review from Lecture 2 CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I Vectors are dynamically-sized arrays Vectors, strings and other containers should be: passed by reference when they are to
More informationUnit 7: Introduction to Object-Oriented Programming
: to Object-Oriented Programming Programming 2 Copy ructors 2013-2014 Index 1 to Object-Oriented Programming 2 Core concepts Copy ructors 3 4 5 Definition Copy ructors The OOP is a programming paradigm
More informationUniversità degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M
Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one
More informationKOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays
More informationChapter 17 - C++ Classes: Part II
Chapter 17 - C++ Classes: Part II 17.1 Introduction 17.2 const (Constant) Objects and const Member Functions 17.3 Composition: Objects as Members of Classes 17.4 friend Functions and friend Classes 17.5
More informationC++ Polymorphism. Systems Programming
C++ Polymorphism Systems Programming C++ Polymorphism Polymorphism Examples Relationships Among Objects in an Inheritance Hierarchy Invoking Base-Class Functions from Derived-Class Objects Aiming Derived-Class
More informationComputer Programming Inheritance 10 th Lecture
Computer Programming Inheritance 10 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved 순서 Inheritance
More informationProgramming C++ Lecture 2. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 2 Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Function Templates S S S We can do function overloading int boxvolume(int side) { return side
More informationTutorial letter 202/2/2018
COS1512/202/2/2018 Tutorial letter 202/2/2018 Introduction to Programming II COS1512 Semester 2 School of Computing This tutorial letter contains the solution to Assignment 2 IMPORTANT INFORMATION: Please
More informationIntroduction to Computer Science I
Introduction to Computer Science I Classes Janyl Jumadinova 5-7 March, 2018 Classes Most of our previous programs all just had a main() method in one file. 2/13 Classes Most of our previous programs all
More informationFriends and Overloaded Operators
Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software
More informationOperator overloading: extra examples
Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading
More informationFriends and Overloaded Operators
Friends and Overloaded Operators Friend Function Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software
More informationKing Abdulaziz University Faculty of Computing and Information Technology Computer Science Department
King Abdulaziz University Faculty of Computing and Information Technology Computer Science Department CPCS204, 1 st Term 2014 Program 1: FCIT Baqalah Assigned: Monday, February 10 th, 2014 Due: Thursday,
More informationReview: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements
Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja
More informationKing Abdulaziz University Faculty of Computing and Information Technology Computer Science Department
King Abdulaziz University Faculty of Computing and Information Technology Computer Science Department CPCS204, 1 st Term 2014 Program 2: FCIT Baqalah Assigned: Thursday, September 26 th, 2013 Due: Wednesday,
More informationCSCI 102 Fall 2010 Exam #1
Name: USC Username: CSCI 102 Fall 2010 Exam #1 Problems Problem #1 (14 points) Problem #2 (15 points) Problem #3 (20 points) Problem #4 (16 points) Problem #5 (35 points) Total (100 points) Problem 1 Short
More informationSheet 3. void SetPayRate(float rate); float CalcGrossPay(); void Validation(ifstream & in); //employee.h. //operator overloading. #include <fstream.
1 //employee.h #include Sheet 3 #include #include #include const float PAYRATE_MIN = 0.0; const float PAYRATE_MAX = 50.0; const float HOURS_MIN = 0.0; const
More informationLAB 4.1 Relational Operators and the if Statement
LAB 4.1 Relational Operators and the if Statement // This program tests whether or not an initialized value of num2 // is equal to a value of num1 input by the user. int main( ) int num1, // num1 is not
More informationKEY printed. Do not start the test until instructed to do so! CS 2704 Object-Oriented Software Design and Construction Test 1.
VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Instructions: Print your name in the space provided below. Answer each question in the space provided. If you want partial credit, justify
More informationCSE 303, Spring 2009 Final Exam Wednesday, June 10, 2009
CSE 303, Spring 2009 Final Exam Wednesday, June 10, 2009 Personal Information: Name: Student ID #: You have 110 minutes to complete this exam. You may receive a deduction if you keep working after the
More informationPreview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions
Preview Constant Objects and Constant Functions Composition: Objects as Members of a Class Friend functions The use of Friend Functions Some objects need to be modifiable and some do not. A programmer
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes September 14, 2004 Structure Definitions 2 Structures Aggregate data types built using elements of other types
More informationHIBERNATE - INTERCEPTORS
HIBERNATE - INTERCEPTORS http://www.tutorialspoint.com/hibernate/hibernate_interceptors.htm Copyright tutorialspoint.com As you have learnt that in Hibernate, an object will be created and persisted. Once
More informationHandout 7. Defining Classes part 1. Instance variables and instance methods.
Handout 7 CS180 Programming Fundamentals Spring 15 Page 1 of 8 Handout 7 Defining Classes part 1. Instance variables and instance methods. In Object Oriented programming, applications are comprised from
More informationOther Loop Options EXAMPLE
C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24, 2004 2 Classes Structure Definitions 3 Structures Aggregate data types built using elements of other
More informationLab 1. largest = num1; // assume first number is largest
Lab 1 Experiment 1 Complete and execute the following program #include using std::cout; using std::cin; using std::endl; int main() { int number1; int number2; int number3; int smallest; int
More informationSection #4 Solutions
Nick Troccoli Section #4 CS 106X Week 5 Section #4 Solutions 1. Pointer Trace (pointers, dynamic memory, tracing) Line 1: 9-3 1 0xcc00 Line 2: -7 9 6 0x555500 Line 3: 5-7 2 0xdd00 Line 4: 5 0x555500 9-3
More informationObject Oriented Programming 2012
1. Write a program to display the following output using single cout statement. Maths = 90 Physics =77 Chemestry =69 2. Write a program to read two numbers from the keyboard and display the larger value
More informationArrays in C++ Instructor: Andy Abreu
Arrays in C++ Instructor: Andy Abreu Reason behind the idea When we are programming, often we have to process a large amount of information. We can do so by creating a lot of variables to keep track of
More informationAdd Subtract Multiply Divide
ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient
More informationAbstract Data Types. Different Views of Data:
Abstract Data Types Representing information is fundamental to computer science. The primary purpose of most computer programs is not to perform calculations, but to store and efficiently retrieve information.
More informationFundamentals of Programming Session 25
Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationVARIABLE, OPERATOR AND EXPRESSION [SET 1]
VARIABLE, OPERATOR AND EXPRESSION Question 1 Write a program to print HELLO WORLD on screen. Write a program to display the following output using a single cout statement. Subject Marks Mathematics 90
More informationInteger Data Types. Data Type. Data Types. int, short int, long int
Data Types Variables are classified according to their data type. The data type determines the kind of information that may be stored in the variable. A data type is a set of values. Generally two main
More informationInheritance Introduction. 9.1 Introduction 361
www.thestudycampus.com Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship Between Superclasses and Subclasses 9.4.1 Creating and Using a CommissionEmployee
More informationCSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1]
CSC 138 Structured Programming CHAPTER 3: RECORDS (STRUCT) [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define records (structures) that contain array data type as one of the
More informationUEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter
UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter What you will learn from Lab 7 In this laboratory, you will understand how to use typical function prototype with
More informationQuestion 1 Consider the following structure used to keep employee records:
Question 1 Consider the following structure used to keep employee records: struct Employee string firstname; string lastname; float salary; } Turn the employee record into a class type rather than a structure
More information12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.
Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.
More informationBanaras Hindu University
Banaras Hindu University A Course on Software Reuse by Design Patterns and Frameworks by Dr. Manjari Gupta Department of Computer Science Banaras Hindu University Lecture 5 Basic Design Patterns Basic
More informationProgramming Assignment #2
Programming Assignment #2 Due: 11:59pm, Wednesday, Feb. 13th Objective: This assignment will provide further practice with classes and objects, and deepen the understanding of basic OO programming. Task:
More informationSubject: Computer Science
Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program
More informationI BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++
No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)
More informationFundamentals of Programming Session 28
Fundamentals of Programming Session 28 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationCpt S 122 Data Structures. Inheritance
Cpt S 122 Data Structures Inheritance Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Base Classes & Derived Classes Relationship between
More informationAn inline function is one in which the function code replaces the function call directly. Inline class member functions
Inline Functions An inline function is one in which the function code replaces the function call directly. Inline class member functions if they are defined as part of the class definition, implicit if
More informationBBM 102 Introduction to Programming II Spring Inheritance
BBM 102 Introduction to Programming II Spring 2018 Inheritance 1 Today Inheritance Notion of subclasses and superclasses protected members UML Class Diagrams for inheritance 2 Inheritance A form of software
More informationOBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2
More informationREVIEW EXERCISES. Draw an inheritance diagram that shows the relationships between these classes.
Review Exercises 367 11. A derived-class pointer can be converted to a base-class pointer. 12. When a virtual function is called, the version belonging to the actual type of the implicit parameter is invoked.
More informationPointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.
Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference
More informationo Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement
Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise
More informationFundamentals of Programming Session 23
Fundamentals of Programming Session 23 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines
More informationObject oriented programming
Exercises 8 Version 1.0, 11 April, 2017 Table of Contents 1. Polymorphism............................................................... 1 1.1. Publications.............................................................
More information