面向对象程序设计教案(英文)
《面向对象程序设计》(Object-Oriented Programming)教学大纲
《面向对象程序设计》(Object-Oriented Programming)课程教学大纲第一部分大纲说明一、课程的性质和任务《面向对象程序设计》是计算机科学与技术专业本科生的一门必修课程。
面向对象软件开发方法是吸收了软件工程领域有益的概念和有效的方法而发展起来的一种软件开发方法。
它集抽象性、封装性、继承性和多态性于一体,可以帮助人们开发出模块化、数据抽象程度高的,体现信息隐蔽、可复用、易修改、易扩充等特性的程序。
本课程主要介绍面向对象程序设计的方法和C++语言的基本概念。
以C++语言中的面向对象机制为主。
学习者在学习过程中可以通过大量的程序实例和相关练习,逐步掌握C++的面向过程和面向对象的功能,从而掌握面向对象程序设计的基本知识和基本技能。
二、先修课要求有一门程序设计语言基础。
三、课程的教学基本要求1.了解面向对象的基本概念和使用面向对象技术进行程序设计的基本思想。
2.能比较熟练地用C++语言进行一般面向对象的程序设计。
3.初步掌握面向对象编程环境Visual C++的使用。
四、教学方法和教学形式建议1.该课程实践性较强,需要学员多作练习。
2.主持教师需要有比较熟练的编程经验,对Visual C++环境比较熟悉。
3.针对所留习题,可以组织两到三次讨论,以便学员掌握面向对象设计思想。
五、课程教学要求的层次1.掌握:要求学生能够较好地理解,并且能够进行简单分析和判断。
2.了解:要求学生能够一般地知道所学内容。
第二部分多种媒体教材一体化总体设计初步方案一、学时分配24。
第三部分教学内容和教学要求一、面向对象的程序设计方法和C++简介: 3学时教学内容:面向对象程序设计的基本思想及基本概念:对程序的的质量要求;程序的模块化和结构化;为什么要面向对象:从面向过程到面向对象;C++语言发展的历史:面向对象语言分类;C++中支持面向对象的特点;面向对象的软件开发环境与Visual C++。
教学要求:了解:面向对象程序设计的基本思想及基本概念。
面向对象的程序设计教案
对象的建立和编辑
对象的属性、事件和方法
属性 用来描述和反映对象特征的参数。 对象的名称(Name)、标题(Caption)、颜 色(Forecolor、Backcolor) 、字体 (Fontname)、是否可见(Visible)等。
可以通过下列两种方法设置对象的属性: 在属性框中直接设置属性 在程序代码中通过赋值实现 对象.属性=属性值
事件、件过程和事件驱动
事件 单击(Click)、双击(DbClick)、改变 (Chang)、获取焦点(GotFocus)、键盘按 下(KeyPress)等。 事件驱动程序设计
方法
VB已经将一些通用的过程和函数编 好并封装起来,作为方法供用户是 使用 。 [对象].方法 [参数]
Visual Basic最早是由Microsoft公司 在1991年推出的,于1992年、1993 年、1995年、1997年和1998年相 继推出了VB2.0、VB3.0、 VB4.0、VB5.0和VB6.0五个版本。
本章学习目标
启动和退出Visual Basic 了解Visual Basic 的屏幕组成 从菜单栏执行命令 窗口设计器 控件与属性初步 代码窗口 帮助系统的安装与使用
第二章 简单的VB程序设计
程序设计方法的发展
初始的程序设计 (可读性差、可维护性差、通用性差) 结构化的程序设计 1. 模块分割仍然主要针对控制流 2. 仅突出了实现功能的操作方法 面向对象的程序设计OOP (Object Oriented Programming)
UML面向对象建模与设计英文版第二版教学设计 (2)
UML Object-Oriented Modeling and Design TeachingDesign - Second EditionIntroductionObject-oriented design has become an essential skill for software developers in today’s technology-driven world. UML is a visual modeling language that has been developed for object-oriented software design and is widely used in industry today. The second edition of the UML Object-Oriented Modeling and Design is an excellent resource for educators who wish to teach object-oriented design principles in their classroom. In this teaching design, we will explore the structure and content of the second edition of the book and provide an overview of some practical approaches for teaching UML.Chapter 1: Introduction to Object-Oriented DesignThe first chapter of the book introduces the concepts of object-oriented design and UML. Students will learn how to identify and represent objects, classes, and relationships using UML. This chapter also covers the basic UML notation, including class diagrams, object diagrams, and use case diagrams.Lesson plan:•Students will be introduced to the concepts of object-oriented design and UML.•In-class activities will be conducted to help students identify and represent objects, classes, and relationships usingUML.•Students will be given exercises to practice creating class diagrams, object diagrams, and use case diagrams.Chapter 2: Modeling with UMLChapter 2 of the book dives deeper into the modeling aspects of UML. In this chapter, students will learn about the different UML diagrams that can be used to represent different aspects of a system, including class diagrams, object diagrams, statecharts, and activity diagrams. The chapter also covers the generalization and specialization relationships between classes.Lesson plan:•Students will learn about the different UML diagrams that can be used to represent different aspects of a system.•In-class examples will be used to help students understand and create different types of UML diagrams.•Students will be given exercises to practice creating class diagrams, object diagrams, statecharts, and activity diagrams.Chapter 3: Advanced Modeling ConceptsChapter 3 of the book covers advanced modeling concepts using UML. This chapter includes topics such as package diagrams, component diagrams, deployment diagrams, and interaction diagrams.Lesson plan:•Students will learn about advanced modeling concepts using UML.•In-class examples will be used to help students understand and create package diagrams, component diagrams, deploymentdiagrams, and interaction diagrams.•Students will be given exercises to practice creating these advanced UML diagrams.Chapter 4: Object-Oriented Design PrinciplesChapter 4 of the book focuses on object-oriented design principles, including abstraction, encapsulation, inheritance, and polymorphism. Students will learn how to apply these principles in the context of UML modeling.Lesson plan:•Students will learn about object-oriented design principles, including abstraction, encapsulation, inheritance, andpolymorphism.•In-class examples will be used to help students understand how to apply these principles in the context of UML modeling.•Students will be given exercises to practice applying these principles in their UML diagrams.Chapter 5: Design PatternsChapter 5 of the book covers design patterns, which are common solutions to recurring problems in software development. In this chapter,students will learn about the different types of design patterns, such as creational, structural, and behavioral patterns.Lesson plan:•Students will learn about design patterns and their importance in software development.•In-class examples will be used to help students understand the different types of design patterns.•Students will be given exercises to practice applying different types of design patterns in their UML diagrams.ConclusionThe second edition of the UML Object-Oriented Modeling and Design book provides a comprehensive guide to object-oriented design using UML. This teaching design can help educators teach these concepts in a structured and organized manner, using practical examples and exercises. By following the lesson plans outlined in this teaching design, students will gn a strong foundation in UML modeling and object-oriented design principles, which will prepare them well for careers in the software development industry.。
C++面向对象程序设计第六版英文改编版课程设计 (2)
C++ Object-Oriented Programming Design Course Project (English Adaptation of Sixth Edition) IntroductionThis course project ms to demonstrate the implementation of object-oriented programming concepts in C++ by adapting the sixth edition of the textbook to English. The original textbook was written in Chinese and published by Tsinghua University Press. The adaptation process involved translating the text, revising the examples, and updating the content with the latest features of C++.Course ObjectivesThe course objectives of this project are as follows:1.Understand the fundamentals of object-oriented programmingin C++.2.Gn practical experience in developing object-orientedprograms.3.Apply concepts such as inheritance, polymorphism, andencapsulation in C++ programs.4.Develop skills in C++ programming and problem-solvingtechniques.Course ContentThe course content covers the following topics:1.Introduction to Object-Oriented Programming–Definition of object-oriented programming–Advantages of object-oriented programming–Principles of object-oriented programming2.Classes and Objects–Class syntax–Class members–Constructors and destructors–Operator overloading–Friend functions3.Inheritance and Polymorphism–Inheritance syntax–Types of inheritance–Polymorphism and virtual functions–Abstract classes and pure virtual functions4.Encapsulation and Templates–Encapsulation and information hiding–Templates and generic programming5.Exception Handling and File I/O–Exception handling syntax–File I/O using streams–File access modesProject RequirementsThe course project must satisfy the following requirements:1.The project must implement the concepts learned in thecourse.2.The project must demonstrate good programming practices andstyle.3.The project must be well-documented and easy to understand.4.The project must be submitted on time and correctly compiled.Grading PolicyThe course project will be graded using the following criteria:1.Correctness of the codee of object-oriented programming concepts3.Programming style and practices4.Documentation and clarity of the codepleteness of the projectConclusionThe adaptation of the sixth edition of the C++ Object-Oriented Programming Design textbook to English provides an opportunity for students to learn and apply object-oriented programming concepts usingC++. The course project ms to develop skills in C++ programming and problem-solving techniques by implementing the concepts learned in the course. The project requirements, grading policy, and course content ensure that students achieve the course objectives and gn practical experience in developing object-oriented programs.。
面向对象程序设计课程教案
面向对象程序设计课程教案现代计算机科学领域中,面向对象程序设计(Object-oriented programming, OOP)被广泛应用于软件开发中。
作为一种软件设计范式,面向对象程序设计以对象作为程序的基本构建单元,通过组合对象、继承、封装等机制,使得软件开发更加高效、可维护和可重用。
本文旨在设计一份面向对象程序设计课程的教案,以帮助学生更好地理解和运用面向对象程序设计的原理和方法。
一、课程概述面向对象程序设计课程旨在帮助学生掌握面向对象程序设计的基本概念、原则和设计方法,培养学生的面向对象程序设计思维,提高其软件开发的能力。
通过该课程的学习,学生将能够熟练运用面向对象程序设计语言,设计和实现简单的面向对象程序。
二、教学目标1. 理解面向对象程序设计的基本概念,包括类、对象、继承、多态等。
2. 掌握面向对象程序设计的设计原则和模式,如单一职责原则、开放封闭原则、工厂模式等。
3. 能够使用面向对象程序设计语言进行程序设计和开发,含糊创建类、封装属性和方法、定义继承关系。
4. 培养学生良好的软件设计思维和团队合作能力,提高软件开发的效率和质量。
三、教学内容1. 面向对象程序设计概述1.1 面向对象程序设计的基本概念1.2 面向对象程序设计语言概述1.3 面向对象程序设计与其他编程范式的比较2. 面向对象程序设计原则2.1 单一职责原则2.2 开放封闭原则2.3 里氏替换原则2.4 接口隔离原则2.5 依赖倒置原则3. 面向对象程序设计的基本技术3.1 类和对象的定义3.2 封装和信息隐藏3.3 继承和多态3.4 抽象类和接口3.5 异常处理和错误处理4. 面向对象程序设计模式4.1 创建型模式(工厂模式、单例模式等)4.2 结构型模式(适配器模式、装饰器模式等)4.3 行为型模式(观察者模式、策略模式等)四、教学方法1. 理论讲授与案例分析相结合,引导学生深入理解面向对象程序设计的原理和方法。
面向对象程序设计(C++)(双语)课程实验教学大纲(英文)
Object Oriented ProgrammingCourse SyllabusCourse Code: 03874Home Department: School of Information Technology Constitutor: Ding JulingExaminant: Yang YongDate of Constituting (or Verifying): September 2, 2008Teaching Affair DepartmentJiangxi University of Finance & EconomicsObject Oriented ProgrammingCourse SyllabusI Course OverviewChapter 1.A tour of C++ (2H in Class and 2H in Lab)●Learning ObjectivesAfter this chapter, students will know the relationship between C and C++, and their differences; the basic C++ language syntax, and programming the first C++ application.●Contents1.1 Procedural program and modular program1.2 Data abstraction definition1.3 Language and programming1.4 Introduction to C++ grammar●Teaching EssentialsThe essential parts are C++ syntax, programming and using. The hard parts are the relationship and the differences between C and C++.Chapter 2.A tour of the standard library (2H in Class and 2H in Lab)●Learning ObjectivesAfter this chapter, students will know the basic input and output of C++, and the standard libraries.●Contents2.1 Output and input in C++2.2 The iterators of standard library2.3 Algorithms and the function of STL●Teaching EssentialsThe essential part is to know the common standard libraries, such as string, vector, list & map.Chapter 3.Array and pointer (2H in Class and 2H in Lab)●Learning ObjectivesAfter this chapter, students will know the definition of array and pointer, how to use them.●Contents3.1 One dimension array3.2 Two dimension array3.3 Multi dimension array3.4 Array and functions3.5 Pointer operation3.6 New and delete operation●Teaching EssentialsThe essential part is the use of array and pointer.Chapter 4.Functions, Pointer to Function (2H in Class and 4H in Lab)●Learning ObjectivesAfter this chapter, students will know the definition of function, argument passing and the use of pointer to function.●Contents4.1 Function declarations and definitions4.2 Inline function4.3 Static variables4.4 Argument passing in the function4.5 Function overloading4.6 Default argument●Teaching EssentialsThe essential parts are augment passing, use of inline function; and the hard part is overloaded function.Chapter 5.Macros, Namespace (2H in Class)●Learning ObjectivesFather this chapter, students will know the use of macros in C++, the definition and use of namespace.●Contents5.1 Macros in C++5.2 The definition of namespace5.3 Using declarations and directives for namespace●Teaching EssentialsThe essential part is the use of macro and namespace.Chapter 6.Templates (2H in Class)●Learning ObjectivesAfter this chapter, students will know templates and how to use templates to program.●Contents6.1 Templates and instantiations6.2 Function templates and function template overloading6.3 Derivation and templates6.4 Member templates and source code organization●Teaching EssentialsThe essential part is the use of template.Chapter 7.OOP (4H in Class and 4H in Lab)●Learning ObjectivesAfter this chapter, stuedents will know the concept of OOP, the OOP approach ,and its features.●Contents7.1 From Structured Programming to OOP7.2 Introduction to OOP7.3 Abstract7.4 Encapsulation7.5 Inheritance7.6 Polymorphism●Teaching EssentialsThe essential part is the transfer from procedure-oriented programming to object-oriented programming.Chapter 8.Classes and Objects (4H in Class and 4H in Lab)●Learning ObjectivesAfter this chapter, students will know the definition, declare and use of classes and objects, the definition of constructor and destructor, and applying them to analyze and solve the practical problem.●Contents8.1 The definition and declaration of Class8.2 Accessing Manners8.3 Member of class8.4 Copy-constructor8.5 Destructor8.6 Class combination8.7 Static members●Teaching EssentialsThe essential parts are the use of classes, the access of member in class, and use of constructor and destructor.Chapter 9.Operator Overloading (4H in Class and 4H in Lab)●Teaching ObjectivesAfter this chapter, students will know the meaning of overloading, and the use of overload operation, converstion operator, and friens.●Contents9.1 The requirement of operator overloading9.2 Operator function9.3 How to overload operator9.4 Conversion operator9.5 Members and friends9.6 Overloading for other operators●Teaching EssentialsThe essential parts are the use of overload operator and friends.Chapter 10.Derived Classes (4H in Class and 4H in Lab)●Learning ObjectivesAfter this chapter, students will know deriving new class from base class, the access to derived class from base classes, the call sequence of constructor and destructor in derived classes, and multi-inherit and its ambituity.●Contents10.1 Introduction10.2 Single-inherit10.3 Modes of inherit10.4 Multi-inherit10.5 Multi-inherit with inline object10.6 Ambiguity●Teaching EssentialsThe essential parts are the access to inheret, the call of constructor and destructor; and the hard aprt is the ambiguity in multi-inherit.Chapter 11.Virtual Functions and Pure Virtual Functions (4H in Class and 6H in Lab)●Learning ObjectivesAfter this chapter, students will know the concepts of virtual function and pure virtual function, and how to use them.●Contents11.1 Virtual base class11.2 Rules of assignment in inherit11.3 Virtual functions11.4 Pure virtual functions and Abstract ClassesTeaching EssentialsThe essential parts are the design and use of virtual function; and the hard parts are the design and use of pure virtual function.。
面向对象程序设计-课堂教学教案-1
⾯向对象程序设计-课堂教学教案-1《⾯向对象程序设计》课堂教学教案第1章 C#概述1.1⾯向对象程序设计向对象(OO)程序设计,以维基百科的解释:⾯向对象程序设计(英语:Object-oriented programming,缩写:OOP),指⼀种程序设计范型,同时也是⼀种程序开发的⽅法。
它将【对象作为程序的基本单元,将程序和数据封装其中,以提⾼软件的重⽤性、灵活性和扩展性】。
简略来说,⾯向对象程序设计,指采⽤了⾯向对象的⽅法来进⾏程序设计。
设计指⼀种把计划、规划、设想通过视觉传达出来的活动过程,它是⼀种创造性,积累性,实践性的⼯作。
1.⾯向过程程序设计⾯向过程程序设计不是⾯向对象程序设计的前提,从⾯向过程谈起主要是因为⾃⾯向对象(OO)程序设计⼀提出,就有太多的两者对⽐。
C语⾔是⾯向过程的代表,它在1972年由贝尔实验室的D.M.Ritchie提出,在Unix系统中⼤放异彩,直⾄今天在系统软件,图形动画,嵌⼊开发等众多领域中还保持着旺盛的⽣命⼒。
程序设计这个概念,伴随着程序开发被提出,最简略的被描述为:程序设计=数据结构+算法,通俗⼀点的说程序设计指的是设计、编制、调试程序的⽅法和过程。
缺点:数据与过程分离;代码复⽤性差;不能很好地适应需求变化;后期维护困难。
注意:此处通过例程说明,使学⽣真正理解上述缺点。
并告诉学⽣,这并不意味着⾯向过程程序设计就out了。
2.⾯向对象程序设计⾯向对象程序设计以⼈类的⾃然思维⽅式建⽴问题域描述。
以抽象、封装、继承、多态等⽅式来认识问题和解决问题。
强调以现实世界中的客观事物为中⼼,⽽不是以功能为中⼼。
⾯向对象程序设计的特点:【程序设计过程⾃然、更易于理解;容易实现软件复⽤;能够较好地适应需求变化;有利于后期维护。
】【注意:此处通过例程说明,使学⽣真正理解上述优点。
】⽤例:1:struct Data2: {3:int d;4: };5:void increase_data(Data* data)6: {7: printf("过程调⽤,数据为: %d", ++data->d);8: }9: increase_data(&Data());到1:public class DataWorker2: {3:private int data;4:public void Increase()5: {6: Console.WriteLine("对象调⽤,数据为: {0}", ++data);7: }8: }9:new DataWorker().Increase();1.2C#及.NET Framework1.C#简介C#是微软公司发布的、简洁的、功能强⼤的、类型安全的,由C和C++衍⽣出来的⾯向对象的编程语⾔,开发⼈员可以使⽤它构建在.NET Framework上运⾏的各种安全、可靠的应⽤程序。
面向对象程序设计(双语)教学大纲
《面向对象程序设计(C++)》(双语)课程教案大纲课程编号:03874制定单位:信息管理学院执笔人:杨巨成审核人:方志军修订时间:2009年8月30日江西财经大学教务处《面向对象程序设计(C++)》(双语)课程教案大纲一、课程总述二、教案时数分配三、单元教案目的、教案重难点和内容设置Chapter 1Overview of the book and OOP【Teaching Target】After learning this chapter, the student will know the structure of the book, the advice of how to use C++ and some background information about C++. In addition, the student should learn the main characteristics of OOP language. Finally, the student should grasp how to design a C++ program in VC++.【Emphases】Four main characteristics of C++, the difference between C and C++.【Main contents】(1)Contents of this book(2)Material and reference books(3)Main characteristics of OOP(4)Design C++ program in VC++Chapter 2 A tour of C++【Teaching Target】After learning this chapter, the student will know the history of C++ and what is C++. The student will know the conventional procedural program and modular program. Then, the student will learn what the data abstraction is in C++ and some examples of how to define class by the OOP language.【Emphases】What is modular program, how to define data abstraction and its usage.【Main contents】(1)What is C++(2)Procedural programming(3)Modular programming(4)Data abstraction(5)Object-Oriented ProgrammingChapter 3A tour of the standard library【Teaching Target】After learning this chapter, the student will know the principal of standard library and its main function. When designing the C++ program, the student can use the standard library in the program, which can help to improve the efficiency of the program.【Emphases】 Grasp some typical standard library functions, such as string, vector, list and map.【Main contents】(1)Output and input in C++(2)Strings in C++(3)The containers of standard library(4)Algorithms and math of standard library(5)Standard Library FacilitiesChapter 4 Functions【Teaching Target】After learning this chapter,the student will know the declaration and definition of the function, the action scope of the function and its returning type as well as inline functions and static variables. Finally, the student will know the call of the function, the recursive function as well as the function overloading.【Emphases】Grasp what is static variables and function overloading and know how to use them.【Main contents】(1)Function declarations and definitions(2)Inline function(3)Static variables(4)Argument passing in the function(5)Function overloading(6)Default argumentChapter 5 Pointer to Function, Macros, Namespace【Teaching Target】After learning this chapter, the student will know the pointer to function and its difference to pointer function, the macros and its correct use in the program, as well as the definition and use of namespace. Finally, the student will know how to use declarations and directives for namespace in the program.【Emphases】 Function pointer and namespace.【Main contents】(1)Concept of Pointer to Function, and its use in C++(2)Macros in C++(3)The definition of namespace(4)Using declarations and directives for namespaceChapter 6 Classes【Teaching Target】After learning this chapter, the student will know the role of class and the definition of class. The student will also know what the object is and its difference to class.【Emphases】The difference of public members and private members of a class. The threedifferent access control methods.【Main contents】(1)Characteristics of OOP(2)The definition and declaration of Class(3)Accessing Manners(4)Member of classChapter 7 Constructor & Destructor【Teaching Target】After learning this chapter, the student will know constructors and destructors ofa class, the combination of class as well as the static members of the class.【Emphases】How to define class with constructors and destructors. Understanding the mechanism of class combination and static members.【Main contents】(1)Constructor(2)Copy-constructor(3)Destructor(4)Class combination(5)Static membersChapter 8Pointers and Class Supplement【Teaching Target】After learning this chapter, the student will know the definition and usage of pointers in C++. The student will also know how to use pointers for class and object, the mechanism of constant member functions and default constructors as well as multi-objects as members for a class.【Emphases】The usage of pointers in class for constructors and destructors aswell as for objects. Understanding the mechanism of class with multi-objects as members in the class.【Main contents】(1)Pointers(2)Pointers in class(3)Objects and Pointers(4)Constant Member Functions(5)Default constructors(6)Multi-Objects as MembersChapter 9Operator overloading【Teaching Target】This chapter is given to show:1) the characteristics of friend function and how to define and use it. 2) how to define operator overloading functions by member functions and nonmember functions or friend functions. 3) several typical definitions of operator overloading functions. 4) the mechanism of constructing a string class by using operator overloading.【Emphases】The difference of member functions and friend functions. How to define operator loading in case of member functions and nonmember functions. Understanding the definition of a string class by operator overloading.【Main contents】(1)Friend(2)The requirement of operator overloading(3)Operator function(4)How to overload operator(5)Members and friends(6)Conversion operator(7)Overloading for other operators(8)A string classChapter 10Derived classes【Teaching Target】This chapter is given to show:1)how to define derived class and its member functions in the situation of single-inherit and multi-inherit。
(完整版)面向对象程序设计教案(2024)
3
类是对象的抽象描述,而对象是类的具体实现。 类定义了对象的结构和行为,而对象则是类的一 个实例。
2024/1/30
8
封装、继承和多态
2024/1/30
封装(Encapsulation)
封装是面向对象编程的核心思想之一,它将对象的属性和方法封装在类中,隐藏内部实现 细节,只对外提供必要的接口。封装提高了代码的可维护性和安全性。
Java语言的特点
详细阐述Java语言的面向对象、跨平台、安全性等核心特 性。
Java开发环境搭建
指导学生安装和配置Java开发工具包(JDK)和集成开发 环境(IDE)。
12
基本数据类型与运算符
基本数据类型
详细讲解Java中的整数类型( byte、short、int、long)、浮 点类型(float、double)、字符
2024/1/30
35
对未来学习建议
2024/1/30
深入学习面向对象的设计原则和设计模式
01
建议学生继续深入学习面向对象的设计原则和设计模式,掌握
更多的架构和框架。
实践项目经验
02
鼓励学生多参与实际项目,积累项目经验,提高编程能力和解
决问题的能力。
拓展知识面
03
建议学生拓展知识面,学习其他相关的编程语言和技术,如
2024/1/30
17
异常处理机制
异常定义
异常类型
异常处理流程
异常是程序在运行时出现的非正常情 况,如输入错误、文件找不到、网络 中断等。Java使用异常处理机制来处 理程序中的异常情况。
Java中的异常分为两大类,即检查型 异常(Checked Exceptions)和非 检查型异常(Unchecked Exceptions)。检查型异常需要在方 法声明中抛出,并在调用该方法时捕 获处理;非检查型异常则不需要在方 法声明中抛出,可以在任何地方抛出 。
2024《面向对象程序设计》教案
目录•课程介绍与目标•面向对象基础概念•Java语言基础知识点梳理•类和对象深入剖析•继承、多态与接口实现技巧•异常处理机制•常用设计模式简介•实战项目:简单图形绘制系统01课程介绍与目标课程背景及意义面向对象程序设计(Object-Oriented Programming,OOP)是一种编程范式。
OOP以对象为基础,强调对象的属性和方法,通过类和对象实现代码的重用和封装。
OOP具有继承、多态等特性,可提高代码的可维护性和可扩展性。
面向对象程序设计概念010204课程目标与要求掌握面向对象程序设计的基本概念和思想。
学会使用Java等面向对象编程语言进行程序设计。
理解面向对象程序设计的原则和设计模式。
能够运用面向对象方法分析和解决实际问题。
03教材与参考资料教材参考资料02面向对象基础概念对象与类定义对象类属性与方法实现属性方法方法是对象可执行的操作或行为,用于改变对象的状态或与其他对象交互。
例如,一个人可能有走路、说话等方法。
封装、继承和多态性原理封装01继承02多态性03抽象类与接口应用抽象类抽象类是一种特殊的类,不能被实例化,只能作为其他类的基类。
它定义了子类应具有的公共接口,但不提供具体的实现。
抽象类可以包含抽象方法和非抽象方法。
接口接口是一种完全抽象的类,只定义了一组方法的签名,没有具体的实现。
接口可以被多个类实现,一个类也可以实现多个接口。
接口用于定义对象之间的通信协议,实现不同类之间的松耦合。
03Java语言基础知识点梳理面向对象平台无关性安全性自动内存管理Java语言概述及特点数据类型、变量和运算符变量数据类型Java中的变量包括局部变量、实例变量和类变量(静态变量),每种变量都有其作用域和生命周期。
运算符流程控制语句条件语句Java中的条件语句包括if语句和switch语句,用于根据条件执行不同的代码块。
循环语句Java中的循环语句包括for循环、while循环和do-while循环,用于重复执行某段代码直到满足特定条件。
面向对象程序设计原理及应用实验 英语
面向对象程序设计原理及应用实验英语English:Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of objects, which can contain data and code to manipulate that data. The principles of OOP include encapsulation, inheritance, and polymorphism, which provide a framework for designing software in a modular and reusable way. Encapsulation allows the bundling of data and methods that operate on that data into a single unit, protecting it from outside interference and misuse. Inheritance enables the creation of new classes based on existing ones, allowing for code reuse and the formation of a hierarchy of classes. Polymorphism allows for the same method to behave differently based on the object it is being called on. OOP has many practical applications, such as modeling real-world objects and interactions, organizing complex systems into manageable units, and facilitating collaboration among programmers by providing a common language and framework for communication and problem-solving.中文翻译:面向对象编程(OOP)是一种围绕对象概念展开的编程范式,对象可以包含数据和操作数据的代码。
面向对象程序设计(英文)
Object-Oriented ProgrammingObject-oriented programming is based on three fundamental concepts: data abstraction, inheritance, and dynamic binding. In C++ we use classes for data abstraction and class derivation to inherit one class from another: A derived class inherits the members of its base class(es). Dynamic binding lets the compiler determine at run time whether to use a function defined in the base or derived class.Inheritance and dynamic binding streamline our programs in two ways: They make it easier to define new classes that are similar, but not identical, to other classes, and they make it easier for us to write programs that can ignore the details of how those similar types differ.。
Many applications are characterized by concepts that are related but slightly different. For example, our bookstore might offer different pricing strategies for different books. Some books might be sold only at a given price. Others might be sold subject to some kind of discount strategy. We might give a discount to purchasers who buy a specified number of copies of the book. Or we might give a discount for only the first few copies purchased but charge full price for any bought beyond a given limit.Object-oriented programming (OOP) is a good match to this kind of application. Through inheritance we can define types that model the different kinds of books. Through dynamic binding we can write applications that use these types but that can ignore the type-dependent differences.The ideas of inheritance and dynamic binding are conceptually simple but have profound implications for how we build our applications and for the features that programming languages must support. Before covering how C++ supports OOP, we'll look at the concepts that are fundamental to this style of programming.An OverviewThe key idea behind OOP is polymorphism. Polymorphism is derived from a Greek word meaning "many forms." We speak of types related by inheritance as polymorphic types, because in many cases we can use the "many forms" of a derived or base type interchangeably. As we'll see, in C++, polymorphism applies only to references or pointers to types related by inheritance.InheritanceInheritance lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different. Members defined by the base class are inherited by its derived classes. The derived class can use, without change, those operations that do not depend on the specifics of the derived type. It can redefine those member functions that do depend on its type, specializing the function to take into account the peculiarities of the derived type. Finally, a derived class may define additional members beyond those it inherits from its base class.Classes related by inheritance are often described as forming an inheritance hierarchy. There is one class, referred to as the root, from which all the other classes inherit, directly or indirectly. In our bookstore example, we will define a base class, which we'll name Item_base, to represent undiscounted books. From Item_base we will inherit a second class, which we'll name Bulk_item, to represent books sold with a quantity discount.At a minimum, these classes will define the following operations:● an operation named book that will return the ISBN● an operation named net_price that returns the price for purchasinga specified number of copies of a bookClasses derived from Item_base will inherit the book function without change: The derived classes have no need to redefine what it means to fetch the ISBN. On the other hand, each derived class will need to define its own version of the net_price function to implement an appropriate discount pricing strategy.In C++, a base class must indicate which of its functions it intends for its derived classes to redefine. Functions defined as virtual are ones that the base expects its derived classes to redefine. Functions that the base class intends its children to inherit are not defined as virtual.Given this discussion, we can see that our classes will define three (const) member functions:• A nonvirtual function, std::string book(), that returns the ISBN.It will be defined by Item_base and inherited by Bulk_item.•Two versions of the virtual function, double net_price(size_t), to return the total price for a given number of copies of a specificbook. Both Item_base and Bulk_item will define their own versions of this function.Dynamic BindingDynamic binding lets us write programs that use objects of any type in an inheritance hierarchy without caring about the objects' specific types. Programs that use these classes need not distinguish between functions defined in the base or in a derived class.For example, our bookstore application would let a customer select several books in a single sale. When the customer was done shopping, the application would calculate the total due. One part of figuring the final bill would be to print for each book purchased a line reporting the total quantity and sales price for that portion of the purchase.We might define a function named print_total to manage this part of the application. The print_total function, given an item and a count, should print the ISBN and the total price for purchasing the given number of copies of that particular book. The output of this function should look like:ISBN: 0-201-54848-8 number sold: 3 total price: 98ISBN: 0-201-82470-1 number sold: 5 total price: 202.5Our print_total function might look something like the following:// calculate and print price for given number of copies, applying any discountsvoid print_total(ostream &os,const Item_base &item, size_t n){os << "ISBN: " << item.book() // calls Item_base::book<< "\tnumber sold: " << n << "\ttotal price: "// virtual call: which version of net_price to call is resolved at run time<< _price(n) << endl;}The function's work is trivial: It prints the results of calling book and net_price on its item parameter. There are two interesting things about this function.First, even though its second parameter is a reference to Item_base, we can pass either an Item_base object or a Bulk_item object to this function.Second, because the parameter is a reference and the net_price function is virtual, the call to net_price will be resolved at run time. The version of net_price that is called will depend on the type of the argument passed to print_total. When the argument to print_total is a Bulk_item, the version of net_price that is run will be the one defined in Bulk_item that applies a discount. If the argument is an Item_base object, then the call will be to the version defined by Item_base.C++, dynamic binding happens when a virtual function is called through a reference (or a pointer) to a base class. The fact that a reference (or pointer) might refer to either a base- or a derived-class object is the key to dynamic binding. Calls to virtual functions made through a reference (or pointer) are resolved at run time: The function that is called is the one defined by the actual type of the object to which the reference (or pointer) refers.Defining Base and Derived ClassesIn many ways, base and derived classes are defined like other classes we have already seen. However, there are some additional features that are required when defining classes in an inheritance hierarchy. This section will present those features. Subsequent sections will see how use of these features impacts classes and the programs we write using inherited classes.Defining a Base ClassLike any other class, a base class has data and function members that define its interface and implementation. In the case of our (very simplified) bookstore pricing application, our Item_base class defines the book and net_price functions and needs to store an ISBN and the standard price for the book:// Item sold at an undiscounted price// derived classes will define various discount strategiesclass Item_base {public:Item_base(const std::string &book = "",double sales_price = 0.0):isbn(book), price(sales_price) { }std::string book() const { return isbn; }// returns total sales price for a specified number of items // derived classes will override and apply different discount algorithmsvirtual double net_price(std::size_t n) const{ return n * price; }virtual ~Item_base() { }private:std::string isbn; // identifier for the itemprotected:double price; // normal, undiscounted price};For the most part, this class looks like others we have seen. It defines a constructor along with the functions we have already described. That constructor uses default arguments (Section 7.4.1, p. 253), which allows it to be called with zero, one, or two arguments. It initializes the data members from these arguments.The new parts are the protected access label and the use of the virtual keyword on the destructor and the net_price function. We'll explain virtual destructors in Section 15.4.4 (p. 587), but for now it is worth noting that classes used as the root class of an inheritance hierarchy generally define a virtual destructor.Base-Class Member FunctionsThe Item_base class defines two functions, one of which is preceded by the keyword virtual. The purpose of the virtual keyword is to enable dynamic binding. By default, member functions are nonvirtual. Calls to nonvirtual functions are resolved at compile time. To specify that a function is virtual, we precede its return type by the keyword virtual. Any nonstatic member function, other than a constructor, may be virtual. The virtual keyword appears only on the member-function declaration inside the class. The virtual keyword may not be used on a function definition that appears outside the class body.Access Control and InheritanceIn a base class, the public and private labels have their ordinary meanings: User code may access the public members and may not access theprivate members of the class. The private members are accessible only to the members and friends of the base class. A derived class has the same access as any other part of the program to the public and private members of its base class: It may access the public members and has no access to the private members.Sometimes a class used as a base class has members that it wants to allow its derived classes to access, while still prohibiting access to those same members by other users. The protected access label is used for such members. A protected member may be accessed by a derived object but may not be accessed by general users of the type.Our Item_base class expects its derived classes to redefine the net_price function. To do so, those classes will need access to the price member. Derived classes are expected to access isbn in the same way as ordinary users: through the book access function. Hence, the isbn member is private and is inaccessible to classes that inherit from Item_base.protected MembersThe protected access label can be thought of as a blend of private and public:●Like private members, protected members are inaccessible to usersof the class.●Like public members, the protected members are accessible to classesderived from this class.In addition, protected has another important property:A derived object may access the protected members of its base class only through a derived object. The derived class has no special access to the protected members of base type objects.As an example, let's assume that Bulk_item defines a member function that takes a reference to a Bulk_item object and a reference to an Item_base object. This function may access the protected members of its own object as well as those of its Bulk_item parameter. However, it has no special access to the protected members in its Item_base parameter:void Bulk_item::memfcn(const Bulk_item &d, const Item_base &b){// attempt to use protected memberdouble ret = price; // ok: uses this->priceret = d.price; // ok: uses price from a Bulk_item objectret = b.price; // error: no access to price from an Item_base }The use of d.price is okay, because the reference to price is through an object of type Bulk_item. The use of b.price is illegal because Bulk_item has no special access to objects of type Item_base.Derived ClassesTo define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the formclass classname: access-label base-classwhere access-label is one of public, protected, or private, and base-class is the name of a previously defined class. As we'll see, a derivation list might name more than one base class. Inheritance from a single base class is most common and is the topic of this chapter.We'll have more to say about the access label used in a derivation list in Section 15.2.5 (p. 570). For now, what's useful to know is that the access label determines the access to the inherited members. When we want to inherit the interface of a base class, then the derivation should be public.A derived class inherits the members of its base class and may define additional members of its own. Each derived object contains two parts: those members that it inherits from its base and those it defines itself. Typically, a derived class (re)defines only those aspects that differ from or extend the behavior of the base.Defining a Derived ClassIn our bookstore application, we will derive Bulk_item from Item_base, so Bulk_item will inherit the book, isbn, and price members. Bulk_item must redefine its net_price function and define the data members needed for that operation:// discount kicks in when a specified number of copies of same book are sold// the discount is expressed as a fraction used to reduce the normal priceclass Bulk_item : public Item_base {public:// redefines base version so as to implement bulk purchase discount policydouble net_price(std::size_t) const;private:std::size_t min_qty; // minimum purchase for discount to apply double discount; // fractional discount to apply};Each Bulk_item object contains four data elements: It inherits isbn and price from Item_base and defines min_qty and discount. These latter two members specify the minimum quantity and the discount to apply once that number of copies are purchased.Derived Classes and virtual FunctionsOrdinarily, derived classes redefine the virtual functions that they inherit, although they are not requried to do so. If a derived class does not redefine a virtual, then the version it uses is the one defined in its base class.A derived type must include a declaration for each inherited member it intends to redefine. Our Bulk_item class says that it will redefine the net_price function but will use the inherited version of book.Public, Private, and Protected InheritanceAccess to members defined within a derived class is controlled in exactly the same way as access is handled for any other class (Section 12.1.2, p. 432). A derived class may define zero or more access labels that specify the access level of the members following that label. Access to the members the class inherits is controlled by a combination of the access level of the member in the base class and the access label used in the derived class' derivation list.The base class itself specifies the minimal access control for its own members. If a member is private in the base class, then only the base class and its friends may access that member. The derived class has no access to the private members of its base class, nor can it make thosemembers accessible to its own users. If a base class member is public or protected, then the access label used in the derivation list determines the access level of that member in the derived class:•In public inheritance, the members of the base retain their access levels: The public members of the base are public members of the derived and the protected members of the base are protected in the derived.•In protected inheritance, the public and protected members of the base class are protected members in the derived class.•In private inheritance, all the members of the base class are private in the derived class.As an example, consider the following hierarchy:class Base {public:void basemem(); // public memberprotected:int i; // protected member// ...};struct Public_derived : public Base {int use_base() { return i; } // ok: derived classes can access i// ...};struct Private_derived : private Base {int use_base() { return i; } // ok: derived classes can access i};All classes that inherit from Base have the same access to the members in Base, regardless of the access label in their derivation lists. The derivation access label controls the access that users of the derived class have to the members inherited from Base:Base b;Public_derived d1;Private_derived d2;b.basemem(); // ok: basemem is publicd1.basemem(); // ok: basemem is public in the derived classd2.basemem(); // error: basemem is private in the derived classBoth Public_derived and Private_derived inherit the basemem function. That member retains its access level when the inheritance is public, so d1 can call basemem. In Private_derived, the members of Base are private; users of Private_derived may not call basemem.The derivation access label also controls access from indirectly derived classes:struct Derived_from Private : public Private_derived {// error: Base::i is private in Private_derivedint use_base() { return i; }};struct Derived_from_Public : public Public_derived {// ok: Base::i remains protected in Public_derivedint use_base() { return i; }};Classes derived from Public_derived may access i from the Base class because that member remains a protected member in Public_derived. Classes derived from Private_derived have no such access. To them all the members that Private_base inherited from Base are private.Interface versus Implementation InheritanceA publicly derived class inherits the interface of its base class; it has the same interface as its base class. In well-designed class hierarchies, objects of a publicly derived class can be used wherever an object of the base class is expected.Classes derived using either private or protected do not inherit the base-class interface. Instead, these derivations are often referred to as implementation inheritance. The derived class uses the inherited class in its implementation but does not expose the fact of the inheritance as part of its interface.As we'll see in before, whether a class uses interface or implementation inheritance has important implications for users of the derived class.Constructors and Copy ControlThe fact that each derived object consists of the (nonstatic) members defined in the derived class plus one or more base-class subobjectsaffects how derived-type objects are constructed, copied, assigned, and destroyed. When we construct, copy, assign, or destroy an object of derived type, we also construct, copy, assign, or destroy those base-class subobjects.Constructors and the copy-control members are not inherited; each class defines its own constructor(s) and copy-control members. As is the case for any class, synthesized versions of the default constructor and the copy-control members will be used if the class does not define its own versions.Base-Class Constructors and Copy ControlConstructors and copy control for base classes that are not themselves a derived class are largely unaffected by inheritance. Our Item_base constructor looks like many we've seen before:Item_base(const std::string &book = "",double sales_price = 0.0):isbn(book), price(sales_price) { }The only impact inheritance has on base-class constructors is that there is a new kind of user that must be considered when deciding which constructors to offer. Like any other member, constructors can be made protected or private. Some classes need special constructors that are intended only for their derived classes to use. Such constructors should be made protected. protected。
elipic面向对象程序设计课程设计
elipic面向对象程序设计课程设计一、教学目标本课程的教学目标是使学生掌握面向对象程序设计的基本概念、原理和方法,能够运用面向对象的思想分析和解决问题,具备使用面向对象编程语言进行程序设计的能力。
1.掌握面向对象程序设计的基本概念,如类、对象、封装、继承、多态等。
2.了解面向对象程序设计的特点和优势。
3.熟悉常用的面向对象编程语言,如Java、C++等。
4.能够使用面向对象编程语言编写简单的应用程序。
5.能够运用面向对象的思想分析和解决实际问题。
6.具备良好的编程习惯和代码能力。
情感态度价值观目标:1.培养学生对计算机科学的兴趣和热情。
2.培养学生团队合作精神和自主学习能力。
3.培养学生良好的职业道德和责任感。
二、教学内容本课程的教学内容主要包括面向对象程序设计的基本概念、原理和方法,以及常用的面向对象编程语言。
1.面向对象程序设计的基本概念:类、对象、封装、继承、多态等。
2.面向对象程序设计的特点和优势:相对于面向过程程序设计的优点和区别。
3.常用的面向对象编程语言:Java、C++等。
4.面向对象编程语言的基本语法和编程技巧。
5.面向对象的思想在实际问题中的应用。
三、教学方法本课程采用多种教学方法,以激发学生的学习兴趣和主动性。
1.讲授法:通过讲解和示例,使学生掌握面向对象程序设计的基本概念和原理。
2.讨论法:通过小组讨论和问题解答,培养学生的思考和解决问题的能力。
3.案例分析法:通过分析实际案例,使学生了解面向对象程序设计的应用和优势。
4.实验法:通过编程实践,使学生掌握面向对象编程语言的语法和编程技巧。
四、教学资源本课程所需的教学资源包括教材、参考书、多媒体资料和实验设备。
1.教材:选用权威、实用的面向对象程序设计教材,如《面向对象程序设计原理与实践》。
2.参考书:提供相关的面向对象程序设计参考书籍,供学生自主学习和拓展。
3.多媒体资料:制作课件、教学视频等多媒体资料,丰富教学手段,提高学生的学习兴趣。
《面向对象程序设计》教案
C++P r o g r a m D e s i g n An Introduction to Programming and Object-Oriented DesignPart TwoLei YuemingSchool Of Software Engineering, Chongqing UniversityPhone: 65104221 (H)E-mail: ymlei@September, 2006Chapter 7 :The Class Construct and OODDefining objects with attributes and behaviorK e y C o n c e p t s :Class Types♦ Class construct⏹ Allows programmers to define new data types for representing information⏹ Class type objects can have both attribute components and behavior components ⏹Provides the object-oriented programming in C++Terminology♦ Client - Program using a class ♦ Object behaviors⏹Realized in C++ via member functions (methods)♦ Object attributes⏹ Are known as data members in C++Member Functions♦ Provide a controlled interface to data members and object access and manipulation⏹ Create objects of the class⏹ Inspect, mutate, and manipulate object of the class ⏹Can be used to keep data members in a correct state ♦ SetSize() ♦ SetColor() ♦ Draw()♦ Constructors⏹Member functions that initialize an object during its definition RectangleShape R(W, x, y, c, w, h);⏹Factoid♦ Constructors do not have a type⏹ class construct ⏹ information hiding ⏹ encapsulation ⏹ data members ⏹ member functions ⏹ constructors ⏹ inspectors ⏹ mutators ⏹ facilitators⏹ destructor⏹ const functions ⏹ access specification ⏹ public ⏹ private⏹ object-oriented analysis ⏹ object-oriented design⏹Considered superfluous♦Inspectors⏹Member functions that act as a messenger that returns the value of an attribute⏹Example♦RectangleShapes have an inspector GetColor()color CurrColor = R.GetColor();♦Mutators⏹Changes the value of an attribute⏹Example♦RectangleShapes have a mutator SetColor()R.SetColor(Black);♦Facilitators⏹Causes an object to perform some action or service⏹Example♦RectangleShapes have a facilitator Draw()R.Draw();Access♦Public access⏹All clients and class members have access to the public members♦Private access⏹Only class members have access to the private membersA Simple RectangleShape Class♦Consider a simpler version of the RectangleShape than what is defined in rect.h♦Giving the class definition not the implementation♦The definition in rect.h uses inheritance and member functions with default parameters⏹If you are wondering what is missing♦Default constructor parameters♦Member function⏹Erase()♦Inherited member functions⏹HasBorder(), SetBorder(), and ClearBorder()Simple RectangleShape Header File#ifndef RECT_SHAPE_H#define RECT_SHAPE_H#include "ezwin.h"class RectangleShape {public:// constructorRectangleShape(SimpleWindow &Window,float XCoord, float YCoord, const color &c,float Width, float Height);// facilitatorvoid Draw();// inspectorscolor GetColor() const;float GetWidth() const;float GetHeight() const;void GetSize(float &Width, float &Height)const;void GetPosition(float &XCoord, float &YCoord) const;SimpleWindow& GetWindow() const;// mutatorsvoid SetColor(const color &c);void SetPosition(float XCoord, float YCoord);void SetSize(float Width, float Height);private:// data membersSimpleWindow &Window;float thisXCenter;float thisYCenter;color thisColor;float thisWidth;float thisHeight;};#endifAccess Tests♦ConsiderSimpleWindow W("Testing", 20, 10);RectangleShape R(W, 2, 2, Blue, 4, 3);const RectangleShape S(W, 15, 10, Red, 5, 6);♦Can we do the following?⏹color c = R.GetColor();⏹color d = S.GetColor();⏹color d = R.thisColor;⏹R.DetColor(Yellow);⏹S.SetColor(Black);Home worksExercises 7.6Exercises 7.8Exercises 7.20End of Chapter 7Chapter 8 : ImplementingAbstract Data TypesDevelopment and Implementation a ClassK e y C o n c e p t s :Our Goal♦ Well-defined representations that allow objects to be created and used in an intuitive manner⏹User should not have to bother with unnecessary details ♦ Example⏹ programming a microwave to make popcorn should not require a physics courseGolden Rule♦ Use information hiding and encapsulation to support integrity of data⏹Put implementation details in a separate module♦ Implementation details complicate the class declarations⏹ Data members are private so that use of the interface is required♦ Makes clients generally immune to implementation changes♦ Keep it simple – class minimality rule⏹ Implement a behavior as a nonmember function when possible ⏹ Only add a behav ior if it is necessaryAbstract Data Type♦ Well-defined and complete data abstraction using the information-hiding principleRational Number Review♦ Rational number⏹Ratio of two integers: a/b♦ Numerator over the denominator♦ Standard operations⏹ Addition Multiplication Subtraction Division♦ Consider⏹ data abstraction⏹ abstract data type (ADT) ⏹ rule of minimality⏹ class minimality principle ⏹ default constructor ⏹ copy constructor ⏹ auxiliary functions ⏹ operator overloading⏹ overloading “<<” and “>>” ⏹ reference return⏹ pseudorandom number⏹ member assignment ⏹ inspectors ⏹ mutators ⏹ facilitators ⏹ destructor⏹ const member functionsRational a(1,2); // a = 1/2Rational b(2,3); // b = 2/3cout << a << " + " << b << " = " << a + b;Rational s; // s = 0/1Rational t; // t = 0/1cin >> s >> t;cout << s << " * " << t << " = " << s * t;♦Observation⏹Natural look that is analogous to fundamental-type arithmetic objectsRational Attributes♦ A numerator and denominator⏹Implies in part a class representation with two private int data members♦NumeratorValue and DenominatorValueRational Public Behaviors♦Rational arithmetic⏹Addition, subtraction, multiplication, and division♦Rational relational⏹Equality and less than comparisons♦Practice rule of class minimality♦Construction⏹Default construction♦Design decision 0/1⏹Specific construction♦Allow client to specify numerator and denominator⏹Copy construction♦Provided automatically♦Assignment⏹Provided automatically♦Insertion and extractionNon-Public Behaviors♦Inspection and mutation of data members⏹Clients deal with a Rational object!Auxiliary Behaviors♦Operations (necessarily public)⏹Arithmetic, relational, insertion, and extraction operations♦Provides the natural form we expect⏹Class definition provides a functional form that auxiliary operators use♦Provides commutativity consistency⏹For C++ reasons 1 + r and r + 1 would not be treated the same if addition was amember operationLibrary Components♦Rational.h⏹Class definitions and library function prototy pesMyProgram.cpp#include <iostream>using namespace std;#include "rational.h"int main(){Rational r;Rational s;cout << "Enter two rationals(a/b): ";cin >> r >> s;Rational Sum = r + s;cout << r << " + " << s << " = " << Sum;return 0;}Producing MyProgram.exe♦Preprocessor combines the definitions and prototypes in iostream and rational headers along with MyProgram.cpp to produce a compilation unit⏹Compiler must be told where to look for Rational.hRational Header File Overview♦File layout⏹Class definition and library prototypes nested within preprocessor statements♦Ensures one inclusion per translation unit⏹Class definition precedes library prototypes#ifndef RATIONAL_H#define RATIONAL_Hclass Rational{// …} ;// library prototyp es …#endifClass Rational Overviewclass Rational // from rational.h{public:// for everybody including clientsprotected:// for Rational member functions and for// member functions from classes derived// from rationalprivate:// for Rational member functions} ;Rational Public Sectionpublic:// default constructorRational();// specific constructorRational(int numer, int denom = 1);// arithmetic facilitatorsRational Add(const Rational &r) const;Rational Multiply(const Rational &r) const;// stream facilitatorsvoid Insert(ostream &sout) const;void Extract(istream &sin);Rational Protected Sectionprotected:// inspectorsint GetNumerator() const;int GetDenominator() const;// mutatorsvoid SetNumerator(int numer);void SetDenominator(int denom);Rational Private Sectionprivate:// data membersint NumeratorValue;int DenominatorValue;Auxiliary Operator Prototypes// after the class definition in rational.hRational operator+( const Rational &r, const Rational &s);Rational operator*( const Rational &r, const Rational &s);ostream& operator<<(ostream &sout, const Rational &s);istream& operator>>(istream &sin, Rational &r); Auxiliary Operator Importance♦Natural look♦Should << be a member?⏹Considerr << cout;Const Powerconst Rational OneHalf(1,2);cout << OneHalf; // legalcin >> OneHalf; // illegalRational Implementation#include <iostream> // Start of rational.cpp#include <string>using namespace std;#include "rational.h"// default constructorRational::Rational(){SetNumerator(0);SetDenominator(1);}♦ExampleRational r; // r = 0/1Remember♦Every class object⏹Has its own data members⏹Has its own member functions♦When a member function accesses a data member⏹By default the function accesses the data member of the object to which it belongs!⏹No special notation needed♦Auxiliary functions⏹Are not class members⏹To access a public member of an object, an auxiliary function must use the dot operator onthe desired objectobject.memberSpecific Constructor// (numer, denom) constructorRational::Rational(int numer, int denom){SetNumerator(numer);SetDenominator(denom);}♦ExampleRational t(2,3); // t = 2/3Rational u(2); // u = 2/1 (why?)Inspectorsint Rational::GetNumerator() const{return NumeratorValue;}int Rational::GetDenominator() const{return DenominatorValue;}♦Where are the following legal?int a = GetNumerator();int b = t.GetNumerator();Numerator Mutatorvoid Rational::SetNumerator(int numer){NumeratorValue = numer;}♦Where are the following legal?SetNumerator(1);t.SetNumerator(2);Denominator Mutatorvoid Rational::SetDenominator(int denom){if (denom != 0) {DenominatorValue = denom;}else {cerr << "Illegal denominator: " << denom<< "using 1" << endl;DenominatorValue = 1;}}♦ExampleSetDenominator(5);Addition FacilitatorRational Rational::Add(const Rational &r) const{int a = GetNumerator();int b = GetDenominator();int c = r.GetNumerator();int d = r.GetDenominator();return Rational(a*d + b*c, b*d);}♦Examplecout << t.Add(u);Multiplication FacilitatorRational Rational::Multiply(const Rational &r) const{int a = GetNumerator();int b = GetDenominator();int c = r.GetNumerator();int d = r.GetDenominator();return Rational(a*c, b*d);}♦Examplet.Multiply(u);Insertion Facilitatorvoid Rational::Insert(ostream &sout) const{sout<<GetNumerator()<<'/'<<GetDenominator();return;}♦Examplet.Insert(cout);♦Why is sout a reference parameter?Basic Extraction Facilitatorvoid Rational::Extract(istream &sin){int numer;int denom;char slash;sin >> numer >> slash >> denom;assert(slash == '/');SetNumerator(numer);SetDenominator(denom);return;}♦Examplet.Extract(cin);Auxiliary Arithmetic OperatorsRational operator+(const Rational &r, const Rational &s){return r.Add(s);}Rational operator*(const Rational &r, const Rational &s){return r.Multiply(s);}♦Examplecout << (t + t) * t;Auxiliary Insertion Operatorostream& operator<<(ostream &sout, const Rational &r){r.Insert(sout);return sout;}♦Why a reference return?♦Note we can do eithert.Insert(cout); cout << endl; // unnaturalcout << t << endl; // naturalAuxiliary Extraction Operator// extracting a Rationalistream& operator>>(istream &sin, Rational &r){r.Extract(sin);return sin;}♦Why a reference return?♦We can do eithert.Extract(cin); // unnaturalcin >> t; // naturalWhat’s Happening Here?♦Suppose the following definitions are in effectRational a(2,3);Rational b(3,4);Rational c(1,2);♦Why do the following statements workRational s(a);Rational t = b;c = a♦C++ has automatically provided us a copy constructor and an assignment operator Copy Construction♦Default copy construction⏹Copy of one object to another in a bit-wise manner♦The representation of the source is copied to the target in a bit-by-bit manner⏹This type of copy is called shallow copying♦Class developers are free to implement their own copy constructor♦Rational does need a special one, but we will define one for the experienceA Rational Copy ConstructorRational::Rational(const Rational &r){int a = r.GetNumerator();int b = r.GetDenomiator();SetNumerator(a);SetDenominator(b);}Rational s(a);Rational t = b;Gang Of Three♦If it is appropriate to define a copy constructor then⏹Consider also defining♦Assignment operator⏹Copy source to target and return target⏹A = B = C♦Destructor⏹Clean up the object when it goes out of scope♦We give the name Gang of three to the⏹Copy constructor, assignment operator, and the destructorA Rational Assignment OperatorRational& Rational::operator =(const Rational &r){int a = r.GetNumerator();int b = r.GetDenomiator();SetNumerator(a);SetDenominator(b);return *this;}a = b;a =b = c;Rational DestructorRational::~Rational(){// nothing to do}Home worksExercises 8.27 ~ 8.33 (As one exercise)Exercises 8.42 ~ 8.43 (As one exercise)End of Chapter 8Chapter 9 :Arrays and VectorsMechanism for representing listsK e y C o n c e p t s :Lists♦ Problem solving often requires information be viewed as a list⏹List may be one-dimensional or multidimensional♦ Analogies⏹ Egg carton ⏹ Apartments ⏹ Cassette carrierArray Terminology♦ List is composed of elementsC++ Restrictions♦ Subscripts are denoted as expressions within brackets: [ ]Basic Array DefinitionExample DefinitionsSubscripting♦ Supposeint A[10]; // array of 10 ints A[0], … A[9]⏹ one-dimensional arrays ⏹ array subscripting ⏹ arrays as parameters⏹ array element as parameters ⏹ character string⏹ Standard Template Library (STL) ⏹ container class ⏹ template class ⏹ vector⏹ vector subscripting ⏹ vector resizing ⏹ string subscripting ⏹ iterators⏹ iterator dereferencing ⏹ vector of vector ⏹ sorting⏹ function InsertionSort() ⏹ function QuickSort() ⏹ searching⏹ function BinarySearch() ⏹ algorithm library ⏹ function find() ⏹ table ⏹ matrices⏹ member initialization list ⏹ multidimensional arrays♦To access individual element must apply a subscript to list name A⏹ A subscript is a bracketed expression also known as the indexArray Elements♦Supposeint A[10]; // array of 10 uninitialized ints♦To access an individual element we must apply a subscript to list name AArray Element Manipulation♦Considerint i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;cin >> A[k]; // where next input value is 3Extracting Values For A Listint A[MaxListSize];int n = 0;int CurrentInput;while((n < MaxListSize) && (cin >> CurrentInput)){A[n] = CurrentInput;++n;}Displaying A List// List A of n elements has already been setfor (int i = 0; i < n; ++i) {cout << A[i] << " ";}cout << endl;Smallest Value♦Problem⏹Find the smallest value in a list of integers♦Input⏹ A list of integers and a value indicating the number of integers♦Output⏹Smallest value in the list♦Note⏹List remains unchanged after finding the smallest value!Preliminary Design♦Realizations⏹When looking for value with distinguishing characteristics, need a way of remembering bestcandidate found so far♦Make it a function -- likely to be used oftenNecessary Information♦Information to be maintained⏹Array with values to be inspected for smallest value⏹Number of values in array⏹Index of current element being considered⏹Smallest value so farA More Detailed Design♦Solution⏹Function that takes array of values and array size as its two in parameters; returns smallest valueseen as its value⏹Initialize smallest value so far to first element⏹For each of the other elements in the array in turn♦If it is smaller than the smallest value so far, update the value of the smallest value so far tobe the current element⏹Return smallest value seen as value of functionPassing An Arrayint ListMinimum(const int A[], int asize) {assert(asize >= 1);int SmallestValueSoFar = A[0];for (int i = 1; i < asize; ++i) {if (A[i] < SmallestValueSoFar ) {SmallestValueSoFar = A[i];}}return SmallestValueSoFar ;}Using ListMinimum()♦What happens with the following?int Number[6];Number[0] = 3; Number[1] = 88; Number[2] = -7;Number[3] = 9; Number[4] = 1; Number[5] = 24;cout << ListMinimum(Number, 6) << endl;int List[3];List[0] = 9; List[1] = 12; List[2] = 45;cout << ListMinimum(List, 3) << endl;Remember♦Arrays are always passed by reference⏹Artifact of C♦Can use const if array elements are not to be modified♦Do not need to include the array size when defining an array parameterSome Useful Functionsvoid DisplayList(const int A[], int n){for (int i = 0; i < n; ++i) {cout << A[i] << " ";}cout << endl;}void GetList(int A[], int &n, int MaxN = 100){for (n = 0; (n < MaxN) && (cin >> A[n]); ++n) { continue;}}Useful Functions Being Usedconst int MaxNumberValues = 25;int Values[MaxNumberValues];int NumberValues;GetList(Values, NumberValues, MaxNumberValues);DisplayList(Values, NumberValues); Searching♦Problem⏹Determine whether a value key is one of the element values♦Does it matter if⏹Element values are not necessarily numbers⏹Element values are not necessarily unique⏹Elements may have key values and other fields Sequential List Searchingint Search(const int List[], int m, int Key) { for (int i = 0; i < m; ++i) {if (List[i] == Key) {return i;}}return m;}Run time is proportional to number of elementsExample Invocationcin >> val;int spot = Search(Values, NumberValues, val);if (spot != NumberValues) {// its there, so display itcout << Values[spot] << endl;}else { // its not there, so add itValues[NumberValues] = val;++NumberValues;}Sorting♦Problem⏹Arranging elements so that they are ordered according to some desired scheme♦Standard is non-decreasing order⏹Why don't we say increasing order?♦Major tasks⏹Comparisons of elements⏹Updates or element movementCommon Sorting Techniques♦Selection sort⏹On ith iteration place the ith smallest element in the ith list location♦Bubble sort⏹Iteratively pass through the list and examining adjacent pairs of elements and if necessary swapthem to put them in order. Repeat the process until no swaps are necessary♦Insertion sort⏹On ith iteration place the ith element with respect to the i-1 previous elements♦In text♦Quick sort⏹Divide the list into sublists such that every element in the left sublist <= to every element in theright sublist. Repeat the Quick sort process on the sublists♦In textSelectionSortvoid SelectionSort(int A[], int n) {for (int i = 0; i < n-1; ++i) {int k = i;for (int j = i + 1; j < n; ++j) {if (A[j] < A[k])k = j;}if (i != k)swap(A[k], A[i]);}}Complexity♦SelectionSort() Question⏹How long does the function take to run♦Proportional to n*n time units, where n is the number of elements in the list♦General question⏹How fast can we sort using the perfect comparison-based method♦The best possible worst case time is proportional ton log n time unitsVectorsFirst-class mechanism for representing listsStandard Template Library♦What is it?⏹Collection of container types and algorithms supporting basic data structuresSTL Container Classes♦Associative⏹map, set♦Adapters⏹priority_queue, queue, and stackVector Class Properties♦Provides list representation comparable in efficiency to arraysExample#include <vector>#include <iostream>using namespace std;int main() {vector<int> A(4, 0); // A: 0 0 0 0A.resize(8, 2); // A: 0 0 0 0 2 2 2 2vector<int> B(3, 1); // B: 1 1 1for (int i = 0; i < B.size(); ++i) {A[i] = B[i] + 2;} // A: 3 3 3 0 2 2 2 2A = B; // A: 1 1 1return 0;}Some Vector Constructors♦vector()⏹The default constructor creates a vector of zero length♦vector(size_type n, const T &val = T())⏹Explicit constructor creates a vector of length n with each element initialized to val ♦vector(const T &V)⏹The copy constructor creates a vector that is a duplicate of vector V.♦Shallow copy!Construction♦Basic constructionvector<T> List;♦Examplevector<int> A; // 0 intsvector<float> B; // 0 floatsvector<Rational> C; // 0 Rationals♦Basic constructionvector<T> List(SizeExpression);♦Examplevector<int> A(10); // 10 intsvector<float> B(20); // 20 floatsvector<Rational> C(5); // 5 Rationalsint n = PromptAndRead();vector<int> D(n); // n ints♦Basic constructionvector<T> List(SizeExpression, Value);♦Examplevector<int> A(10, 3); // 10 3svector<float> B(20, 0.2); // 20 0.2sRational r(2/3);vector<Rational> C(5, r); // 5 2/3sVector Interface♦size_type size() const⏹Returns the number of elements in the vectorcout << A.size(); // display 3♦bool empty() const⏹Returns true if there are no elements in the vector; otherwise, it returns falseif (A.empty()) {// ...}♦vector<T>& operator = (const vector<T> &V)⏹The member assignment operator makes its vector representation an exact duplicate of vector V.♦Shallow copy⏹The modified vector is returnedvector<int> A(4, 0); // A: 0 0 0 0vector<int> B(3, 1); // B: 1 1 1A = B; // A: 1 1 1♦reference operator [](size_type i)⏹Returns a reference to element i of the vector♦Lvalue♦const_reference operator [](size_type i) const⏹Returns a constant reference to element i of the vector♦RvalueExamplevector<int> A(4, 0); // A: 0 0 0 0const vector<int> B(4, 0); // B: 0 0 0 0for (int i = 0; i < A.size(); ++i) {A[i] = 3;} // A: 3 3 3 3for (int i = 0; i < A.size(); ++i) {cout << A[i] << endl; // lvaluecout << B[i] << endl; // rvalue}♦reference at(size_type i)⏹If i is in bounds, returns a reference to element i of the vector; otherwise, throws an exception ♦const_reference at(size_type i) const⏹If i is in bounds, returns a constant reference to element i of the vector; otherwise, throws anexceptionExamplevector<int> A(4, 0); // A: 0 0 0 0for (int i = 0; i <= A.size(); ++i) {A[i] = 3;} // A: 3 3 3 3 ??for (int i = 0; i <= A.size(); ++i) {A.at(i) = 3;} // program terminates// when i is 4♦void resize(size_type s, T val = T())⏹The number of elements in the vector is now s.♦To achieve this size, elements are deleted or added as necessary⏹Deletions if any are performed at the end⏹Additions if any are performed at the end⏹New elements have value valvector<int> A(4, 0); // A: 0 0 0 0A.resize(8, 2); // A: 0 0 0 0 2 2 2 2A.resize(3,1); // A: 0 0 0Function Examplesvoid GetList(vector<int> &A) {int n = 0;while ((n < A.size()) && (cin >> A[n])) {++n;}A.resize(n);}vector<int> MyList(3);cout << "Enter numbers: ";GetList(MyList);Examplesvoid PutList(const vector<int> &A) {for (int i = 0; i < A.size(); ++i) {cout << A[i] << endl;}}cout << "Your numbers: ";PutList(MyList)♦pop_back()⏹Removes the last element of the vector♦push_back(const T &val)⏹Inserts a copy of val after the last element of the vector Examplevoid GetValues(vector<int> &A) {A.resize(0);int Val;while (cin >> Val) {A.push_back(Val);}}vector<int> List;cout << "Enter numbers: ";GetValues(List);Overloading >>istream& operator>>(istream& sin, vector<int> &A) {A.resize(0);int Val;while (sin >> Val) {A.push_back(Val);}return sin;}vector<int> B;cout << "Enter numbers: ";cin >> B;Vector Interface♦reference front()⏹Returns a reference to the first element of the vector♦const_reference front() const⏹Returns a constant reference to the first el ement of the vectorvector<int> B(4,1); // B: 1 1 1 1int& val = B.front();val = 7; // B: 7 1 1 1♦reference back()⏹Returns a reference to the last element of the vector♦const_reference back() const⏹Returns a constant reference to the last element of the vectorvector<int> C(4,1); // C: 1 1 1 1int& val = C.back();val = 5; // C: 1 1 1 5Iterators♦Iterator is a pointer to an element⏹Really pointer abstractionVector Interface♦iterator begin()⏹Returns an iterator that points to the first element of the vector♦iterator end()⏹Returns an iterator that points to immediately beyond the last element of the vectorvector<int> C(4); // C: 0 0 0 0C[0] = 0; C[1] = 1; C[2] = 2; C[3] = 3;vector<int>::iterator p = C.begin();vector<int>::iterator q = C.end();Iterators♦To avoid unwieldy syntax programmers typically use typedef statements to create simple iterator type namestypedef vector<int>::iterator iterator;typedef vector<int>::reverse_iterator reverse_iterator;typedef vector<int>::const_reference const_reference;vector<int> C(4); // C: 0 0 0 0iterator p = C.begin();iterator q = C.end();Iterator Operators♦* dereferencing operator⏹Produces a reference to the object to which the iterator p points*p♦++ point to next element in list⏹Iterator p now points to the element that followed the previous element to which p points++p♦-- point to previous element in list⏹Iterator p now points to the element that preceded the previous element to which p points--ptypedef vector<int>::iterator iterator;typedef vector<int>::reverse_iterator reverse_iterator;vector<int> List(3);List[0] = 100; List[1] = 101; List[0] = 102;iterator p = List.begin();cout << *p; // 100++p;cout << *p; // 101--p;cout << *p; // 100reverse_iterator q = List.rbegin();cout << *q; // 102++q;cout << *q; // 101--q;cout << *q; // 102Vector Interface♦insert(iterator pos, const T &val = T())⏹Inserts a copy of val at position pos of the vector and returns the position of the copy into thevector♦erase(iterator pos)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Contents
(Titles)
Chapter 2: Primitive Data Types and Operations
The MyInput class
Identifiers, Variables, and Constants
Primitive Data Types
Hour
4. [美] C. Thomas Wu.面向对象程序设计导论.北京:电子工业出版社,2004
Homework and requirement
This program lets the user enter the interest rate, number of years, and loan amount and computes monthly payment and total payment.
Teaching requirement:
Introducing Methods
Declaring Methods
Calling Methods
Passing Parameters
Overloading Methodsh Class
Emphases, Difficulties & treatment
The boolean Type and Operators
Shortcut Operators
treatment:
Example 2.2 Computing Mortgages
Example 2.3 Computing Changes
Teaching method
combination of teaching in class and review after class。
2
Teaching aims & requirement
Teaching aims:
Introducing Programming with an Example
Teaching requirement:
The MyInput class
Identifiers, Variables, and Constants
Emphases:
Java Application
Compiling Programs
Executing Applications
A Simple Java Applet
Viewing Java Applets
Difficulties:
Compiling Programs
treatment:
Using example to let student learnCompiling Programs.
Primitive Data Types
Byte, short, int, long, float, double, char, boolean
Emphases, Difficulties & treatment
Emphases:
Declaring Variables
Numeric Type Conversion
switch Statements
while Loops
break and continue
treatment:
Using example to let student learnCompiling Programs.
Teaching method
combination of teaching in class and review after class。
literature
1. [美]H.M.Deitel & P.J.Deitel.Java大学教程(第四版).北京:电子工业出版社,2004
2. [美]John O’Donahue.Java数据库编程.北京:电子工业出版社,2005
3. [美]Ivor Horton.JAVA 2入门经典.中国电力出版社,2005
ExampleComputing Mean and Standard Deviation
Teaching method
combination of teaching in class and review after class。
literature
1. [美]H.M.Deitel & P.J.Deitel.Java大学教程(第四版).北京:电子工业出版社,2004
Emphases:
Calling Methods
Passing Parameters
Overloading Methods
Method Abstraction
Difficulties:
Overloading Methods
Method Abstraction
treatment:
ExampleOverloading the max Method
Operators
Programming Style and Documentation
Hour
2
Teaching aims & requirement
Teaching aims:
Operators
Expressions
Style and Documentation
Syntax Errors, Runtime Errors, and Logic Errors
Teaching requirement:
Using if and if...else
Nested if Statements
Using switch Statements
Repetition Statements
Looping: while, do, and for
Using break and continue
literature
1. [美]H.M.Deitel & P.J.Deitel.Java大学教程(第四版).北京:电子工业出版社,2004
2. [美]John O’Donahue.Java数据库编程.北京:电子工业出版社,2005
3. [美]Ivor Horton.JAVA 2入门经典.中国电力出版社,2005
postscript
teaching plan
Contents
(Titles)
Chapter 4: Methods
Hour
2
Teaching aims & requirement
Teaching aims:
Introducing Methods, Declaring Methods, Calling Methods, Passing Parameters, Pass by Value, Overloading Methods, Method Abstraction, The Math Class,Recursion.
Teaching requirement:
Operators+, -, *, /, %, +=, -=, *=, /=, %=, ++, --
KnowSyntax Errors, Runtime Errors, and Logic Errors
Emphases, Difficulties & treatment
Emphases, Difficulties & treatment
Emphases:
The if...else Statement
Nested if Statements
switch Statements
while Loops
for Loops
break and continue
Difficulties:
Teaching method
combination of teaching in class and review after class
literature
1. [美]H.M.Deitel & P.J.Deitel.Java大学教程(第四版).北京:电子工业出版社,2004
2. [美]John O’Donahue.Java数据库编程.北京:电子工业出版社,2005
Object—Oriented Programming
cases
2007.03
teaching plan
Contents
(Titles)
Chapter 1: Introduction to Java
Hour
2
Teaching aims & requirement
Teaching aims:
What Is Java?
3. [美]Ivor Horton.JAVA 2入门经典.中国电力出版社,2005
4. [美] C. Thomas Wu.面向对象程序设计导论.北京:电子工业出版社,2004
Homework & requirement
Write “hello world” java program.
postscript
4. [美] C. Thomas Wu.面向对象程序设计导论.北京:电子工业出版社,2004
Homework and requirement
This program reads in number of years and loan amount and computes the monthly payment and total payment. The interest rate is determined by number of years.
literature
1. [美]H.M.Deitel & P.J.Deitel.Java大学教程(第四版).北京:电子工业出版社,2004