Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 期末考 Fail 22 MAX 99 Min 5

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

4 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

5 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.

6 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_.

7 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

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

9 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.

10 Figure 7-6 (P.383)

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

12 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 Express, type Ctrl+Shift+C.

13 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.

14 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); };

15 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; }

16 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

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

18 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;

19 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;

20 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 = , or include <cmath>, which can calculate pi = atan(1.0)*4. 3/20

21 2/22 Midterm Exam (1)

22 答題統計

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

24 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);

25 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.

26 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.

27 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?

28 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() {}

29 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.

30 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

31 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 (::).

32 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."; }

33 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!

34 Private Members of a Class

35 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.

36 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.

37 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.

38 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.

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

40 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

41 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.

42 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.

43 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);

44 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).

45 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();

46 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.

47 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.

48 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)


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

Similar presentations


Ads by Google

玻璃钢生产厂家高邮玻璃钢园门头雕塑优质的玻璃钢蚂蚁雕塑玻璃钢人物雕塑工厂山东商业商场美陈销售厂家动物玻璃钢雕塑价格如何泡沫玻璃钢雕塑加工中山绿色种植玻璃钢花盆河北户外商场美陈费用如何制作玻璃钢花盆贵州人物玻璃钢雕塑定制安徽玻璃钢雕塑销售厂家家电商场美陈布置湛江玻璃钢雕塑生产兰州景区玻璃钢雕塑哪家好东城区商场美陈效果图泥塑及玻璃钢雕塑设计贵阳动物玻璃钢雕塑生产厂家京东玻璃钢花盆尺寸及价格吉林景区玻璃钢雕塑定制青羊玻璃钢造型雕塑户外动物园玻璃钢雕塑订制汕头气球玻璃钢雕塑工艺品信阳玻璃钢彩绘雕塑设计上城区玻璃钢雕塑图片玻璃钢仿铜雕塑工艺品陕西锻铜玻璃钢雕塑广州萝岗玻璃钢雕塑玻璃钢雕塑陈靖姑神像浙江玻璃钢造型雕塑吉林人物玻璃钢雕塑供应商香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警汪小菲曝离婚始末遭遇山火的松茸之乡雅江山火三名扑火人员牺牲系谣言何赛飞追着代拍打萧美琴窜访捷克 外交部回应卫健委通报少年有偿捐血浆16次猝死手机成瘾是影响睡眠质量重要因素高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了小米汽车超级工厂正式揭幕中国拥有亿元资产的家庭达13.3万户周杰伦一审败诉网易男孩8年未见母亲被告知被遗忘许家印被限制高消费饲养员用铁锨驱打大熊猫被辞退男子被猫抓伤后确诊“猫抓病”特朗普无法缴纳4.54亿美元罚金倪萍分享减重40斤方法联合利华开始重组张家界的山上“长”满了韩国人?张立群任西安交通大学校长杨倩无缘巴黎奥运“重生之我在北大当嫡校长”黑马情侣提车了专访95后高颜值猪保姆考生莫言也上北大硕士复试名单了网友洛杉矶偶遇贾玲专家建议不必谈骨泥色变沉迷短剧的人就像掉进了杀猪盘奥巴马现身唐宁街 黑色着装引猜测七年后宇文玥被薅头发捞上岸事业单位女子向同事水杯投不明物质凯特王妃现身!外出购物视频曝光河南驻马店通报西平中学跳楼事件王树国卸任西安交大校长 师生送别恒大被罚41.75亿到底怎么缴男子被流浪猫绊倒 投喂者赔24万房客欠租失踪 房东直发愁西双版纳热带植物园回应蜉蝣大爆发钱人豪晒法院裁定实锤抄袭外国人感慨凌晨的中国很安全胖东来员工每周单休无小长假白宫:哈马斯三号人物被杀测试车高速逃费 小米:已补缴老人退休金被冒领16年 金额超20万

玻璃钢生产厂家 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化