論語 先進第十一 暮春者,春服既成 冠者五六人,童子六七人 浴乎沂,風乎舞雩,詠而歸 ㄧˊ 〔~河〕水名,源出中國山東省,至江蘇省入海。

Slides:



Advertisements
Similar presentations
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Advertisements

1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Structuring Your Data Using Classes Chapter 8. What We’ll Cover in Chapter 8 Classes and how they are used The basic components of a class How a class.
Chapter 12: Adding Functionality to Your Classes.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
1 Chapter 7 Defining Your Own Data Types. 2 What Is a struct ?  A structure is a user-defined type You define it using the keyword struct so it is often.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
1 Chapter 8 Destructor & Operator Overloading. 2 Destructor  A destructor is a function that is called when an object is no longer required. A constructor.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Overview of Previous Lesson(s) Over View .NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows.  It.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Chapter 15 - C++ As A "Better C"
Topic: Classes and Objects
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Templates.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
Chapter 14 Templates C++ How to Program, 8/e
Review: Two Programming Paradigms
CS410 – Software Engineering Lecture #11: C++ Basics IV
Classes & Objects.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Chapter 5 Classes.
Pointers and Pointer-Based Strings
Chapter 15: Overloading and Templates
This technique is Called “Divide and Conquer”.
Operator Overloading BCA Sem III K.I.R.A.S.
Pointers and References
Introduction to Classes
Classes and Data Abstraction
7 Arrays.
Dr. Bhargavi Dept of CS CHRIST
Operator overloading Dr. Bhargavi Goswami
Functions Pass By Value Pass by Reference
Classes and Objects.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
7 Arrays.
9-10 Classes: A Deeper Look.
Pointers and Pointer-Based Strings
Submitted By : Veenu Saini Lecturer (IT)
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
黃鶴樓 ~ 崔顥 昔人已乘黃鶴去, 此地空餘黃鶴樓。 黃鶴一去不復返, 白雲千載空悠悠。 晴川歷歷漢陽樹, 芳草萋萋鸚鵡洲。
Chapter 8 (Part 2) Destructor & Operator Overloading (P.331)
9-10 Classes: A Deeper Look.
Video: The Sound of Raining
Chapter 8 Destructor (P.323) & Operator Overloading
Object Oriented Programming (OOP) Lecture No. 12
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
C++ Object Oriented 1.
Creating and Using Classes
SPL – PS3 C++ Classes.
Presentation transcript:

論語 先進第十一 暮春者,春服既成 冠者五六人,童子六七人 浴乎沂,風乎舞雩,詠而歸 ㄧˊ 〔~河〕水名,源出中國山東省,至江蘇省入海。

2013.01 期末考 Fail 22 MAX 99 Min 5

Chapter 7 (cont.) Objects, Classes, and Constructors

Objects A struct allows you to define a variable representing a composite of several fundamental type variables. You can define a rational number (a,b) which represents a/b, but how do you define a function to perform the addition (a,b)+(c,d)=(b*c+a*d, b*d)? You can define a function add(p,q) to perform the addition. Then consider what you need to do for adding complex numbers a+bi. An object provides more advanced features: Encapsulation – an object contains data and functions that operate on those data Inheritance Polymorphism

Class A class is a (user-defined) data type in C++. It can contain data elements of basic types in C++, or of other user-defined types. Just like a struct. The keyword struct and class are almost identical in C++. Let’s see an example.

Example: class CBox (P.363) { public: double m_Length; double m_Width; double m_Height; }; When you define CBox as a class, you essentially define a new data type. The variables m_Length, m_Width, m_Height which you define are called data members of the class. MFC adopts the convention of using the prefix C for all class names. MFC also prefixes data members of classes with m_.

What Does Class Offer More? A class can also contain functions. So, a class combines both the definition of the elementary data, and the methods of manipulating these data. In this book, we call the data and functions within a class data members member functions

Defining a Class class CBox { public: double m_Length; double m_Width; double m_Height; };

Accessing Control in a Class There are public and private data members in a class. Public members can be accessed anywhere. Private members can only be accessed by member functions of a class. See Figure 7-6 in next slide.

Figure 7-6 (P.383)

Declaring Objects of a Class (P.367) CBox box1; CBox box2;

Accessing the Data Members of a Class box2.m_Height = 18.0; direct member selection operator Ex7_02.cpp (P.368) The definition of the class appears outside of the function main(), so it has global scope. You can see the class showing up in the Class View tab. If you did not see Class View in your Visual C++ 2010 Express, type Ctrl+Shift+C.

Member Functions of a Class A member function of a class is a function that its definition or its prototype is within the class definition. It operates on any object of the class It has access to all the members of a class, public or private. Ex7_03.cpp on P.370 box2.Volume() There’s no need to qualify the names of the class members when you accessing them in member functions. The memory occupied by member functions isn’t counted by the sizeof operator.

Positioning a Member Function Definition (1) For better readability, you may put the definition of a member function outside the class definition, but only put the prototype inside the class. class CBOX { public: double m_Length; double m_Width; double m_Height; double Volume(void); };

Positioning a Member Function Definition (2) Now because you put the function definition outside the class, you must tell the compiler that this function belongs to the class CBox. scope resolution operator ( :: ) // Function to calculate the volume of a box double CBox::Volume() { return m_Length*m_Width*m_Height; }

Example: Rational Number #include <iostream> using std::cout; using std::endl; class CRational { public: int p; int q; }; int main() CRational a; a.p = 1; a.q = 3; cout << a.p << '/' << a.q << endl; return 0; } Example: Rational Number

Rational Number (2) Member Functions Print() Reduce() Add() Subtract() Multiply()

Print() #include <iostream> using std::cout; using std::endl; class CRational { public: int p; int q; void Print() cout << p << '/' << q << endl; } }; int main() CRational a; a.p = 1; a.q = 3; cout << a.p << '/' << a.q << endl; a.Print(); return 0;

Multiply() #include <iostream> using std::cout; using std::endl; class CRational { public: int p; int q; void Print() cout << p << '/' << q << endl; } CRational Multiply(CRational b) { p = p * b.p; q *= b.q; return *this; } }; int main() CRational a, b; a.p = 1; a.q = 3; b.p = 2; b.q = 3; a.Multiply(b); a.Print(); return 0;

Exercise Modify Ex7_01.cpp, and replace the struct RECTANGLE with a class CIRCLE. Now the yard, the pool, and two huts belong to the type CIRCLE. Define a member function Area() to calculate the area of the circle. Try to define a member function MoveCircle() to do what it is expected to do. You may define const double pi = 3.14159, or include <cmath>, which can calculate pi = atan(1.0)*4. 3/20

2/22 Midterm Exam (1)

答題統計

白雪歌送武判官歸 ~岑參 北風捲地百草折, 胡天八月即飛雪; 忽如一夜春風來, 千樹萬樹梨花開。 散入珠簾濕羅幕, 狐裘不煖錦衾薄; 將軍角弓不得控, 都護鐵衣冷難著。 瀚海闌干百丈冰, 愁雲黲淡萬里凝。 中軍置酒飲歸客, 胡琴琵琶與羌笛。 紛紛暮雪下轅門, 風掣紅旗凍不翻。 輪臺東門送君去, 去時雪滿天山路; 山迴路轉不見君, 雪上空留馬行處。

Initialize Data Members of an Object Assign the individual value to each member: Hut1.Left = 70; Hut1.Top = 10; Hut1.Right = 95; Hut1.Bottom = 30; It would be great if we have a simpler syntax: RECTANGLE Hut1(70, 10, 95, 30);

Class Constructors A class constructor is a special function which is invoked when a new object of the class is created. You may use the constructor to initialize an object conveniently. It always has the same name as the class. The constructor for class CBox is also named CBox(). It has no return type. You must not even write it as void.

Ex7_04.cpp on P.374 Constructor Definition Object initialization CBox(double lv, double bv, double hv) { cout << endl << “Constructor called.”; m_Length = lv; m_Width = bv; m_Height = hv; } Object initialization CBox box1(78.0, 24.0, 18.0); CBox cigarBox(8.0, 5.0, 1.0); Observe that the string “Constructor called” was printed out twice in the output. Now that you get the concept of how a constructor works in a class, let us see more variations of constructors.

The Default Constructor Try modifying Ex7_04.cpp by adding the following line: CBox box2; // no initializing values When you compile this version of the program, you get the error message: error C2512: ‘CBox’ no appropriate default constructor available Q: Compare with Ex7_02.cpp (P.368). Why the same line “CBox box2” introduced no troubles at that time?

The Default Constructor (2) In Ex7_02.cpp, you did not declare any constructor, so the compiler generated a default no-argument constructor for you. Now, since you supplied a constructor CBox(), the compiler assumes that you will take care of everything well. You can define a default constructor which actually does nothing: CBox() {}

Ex7_05.cpp The default constructor only shows a message. See how the three objects are instantiated. CBox box1(78.0, 24.0, 18.0); CBox box2; CBox cigarBox(8.0, 5.0, 1.0); Pay attention to the 6 lines of output messages.

Assigning Default Parameter Values Recall that we may assign default values for function parameters (P.302). Put the default values for the parameters in the function header. int do_it(long arg1=10, long arg2=20); You can also do this for class member functions, including constructors. Ex7_06.cpp on P.379

Exercise Modify Ex7_06.cpp so that the definition of the Default Constructor is placed outside the body of the class definition. Be sure to use the scope resolution operator (::).

Using an Initialization List in a Constructor It is a common practice to assign initial values to data members with constructors. Instead of using explicit assignment, you could use a different technique: initialization list: // Constructor definition using an initialisation list CBox(double lv = 1.0, double bv = 1.0, double hv = 1.0): m_Length(lv), m_Width(bv), m_Height(hv) { cout << endl << "Constructor called."; }

Making a Constructor Explicit (P.381) If you don’t want the C compiler to perform the implicit conversion, add a keyword explicit to your constructor. Usually a data-type mismatch implies mistakes, but the compiler will allow it if implicit conversion is performed. Suppose you have this constructor: CBox(double side): m_Length(side), m_Width(side), m_Height(side) {} Consider the following code fragment: CBox box; box = 99.0; // assign a double to a CBox The compiler thinks this is valid by converting 99.0 to CBox(99.0). The following constructor also gets implicit conversion that you may not intend. CBox(double lv = 1.0, double bv = 1.0, double hv = 1.0) : m_Length(lv), m_Width(bv), m_Height(Hv) {} The compiler will implicitly convert 99.0 to CBox(99.0, 1.0, 1.0). Declare your constructor explicit to prevent this kind of errors!

Private Members of a Class

Ex7_07.cpp on P.383 The definition of the CBox class now has two sections. public section the constructor CBox() the member function Volume() private section data members m_Length, m_Width, m_Height They can only be accessed by member functions of the same class.

Friend Functions of a Class (P.386) Sometime, for some reason, you want certain selected functions that are not members of a class to be able to access data members of a class. Such functions are called friend functions of a class, and are defined using the keyword friend.

Ex7_08.cpp (P.386) Creating a friend function of a class. // include the prototype in the class definition friend double BoxSurface(CBox aBox); Try to remove this line, and observe what error messages you will get.

The Copy Constructor See the output of Ex7_09.cpp (P.389). The default constructor is only called once. How was box2 created? A copy constructor creates an object of a class by initializing it with an existing object of the same class. Let us wait until the end of this chapter to see how to implement a copy constructor.

Arrays of Objects of a Class Ex7_11.cpp on P.396 CBox boxes[5]; CBox cigar(8.0, 5.0, 1.0);

Static Data Member of a Class When you declare data members of a class to be static, the static data members are defined only once and are shared between all objects of the class. For example, we can implement a “counter” in this way. P.283 Static Variables in a Function

How do you initialize the static data member? You cannot initialize the static data member in the class definition The class definition is simply a blueprint for objects. No assignment statements are allowed. You don’t want to initialize it in a constructor Otherwise the value will be destroyed whenever a new object is created.

Counting Instances Write an initialization statement of the static data member outside of the class definition: int CBox::objectCount = 0; Ex7_12.cpp on P.399 static int objectCount; Declare the count in the public section of CBox class definition. Increment the count in constructors. Initialize the count before main(). The static data members exist even though there is no object of the class at all.

Static Member Functions of a Class The static member functions exist, even if no objects of the class exist. A static function can be called in relation to a particular object: aBox.Afunction(10); or with the class name: CBox::Afunction(10);

Pointers to Class Objects Declare a pointer to CBox CBox* pBox = NULL; Store the address of object cigar in pBox CBox cigar; pBox = &cigar; Call the function Volume() cout << pBox->Volume(); cout << (*pBox).Volume(); In Ex7_10.cpp, the pointer this refer to the current object (P.391).

References to Class Objects Remember, a reference acts as an alias for the object. Define reference to object cigar CBox& rcigar = cigar; Output volume of cigar cout << rcigar.Volume();

Implementing a Copy Constructor (P.405) Consider writing the prototype of a Copy Constructor like this: CBox(CBox initB); What happens when this constructor is called? CBox myBox = cigar; This generates a call of the copy constructor as follows: CBox::CBox(cigar); This seems to be no problem, until you realize that the argument is passed by value. You end up with an infinite number of calls to the copy constructor.

Implementing a Copy Constructor (2) Use a reference parameter CBox::CBox(const CBox& initB) { m_Length = initB.m_Length; m_Width = initB.m_Width; m_Height = initB.m_Height; } If a parameter to a function is a reference, no copying of the argument occurs when the function is called. Declare it as a const reference parameter to protect it from being modified from within the function.

HW: Constructor Modify Ex7_01.cpp. Due: 3/5 (Tuesday) Define a class CRectangle. Define a constructor to initialize Hut1. Define a copy constructor to copy the contents of Hut1 to Hut2. You may also need to modify the data type in MoveRect() and Area() accordingly. Due: 3/5 (Tuesday)