490 likes | 648 Views
Final Revision. Spring, 2011. Overall Assessment. Continuous assessment 20% Attendance 10% Assignments 10% Final examination 80% Close book English Answer in Chinese is allowed Digital dictionary is allowed. Question Types in Final Exam. Multiple choice (40’) Output analysis (20’)
E N D
Final Revision Spring, 2011
Overall Assessment • Continuous assessment 20% • Attendance 10% • Assignments 10% • Final examination 80% • Close book • English • Answer in Chinese is allowed • Digital dictionary is allowed
Question Types in Final Exam • Multiple choice (40’) • Output analysis (20’) • Mistake identification (10’) • Fill-in-the-blank (Program completion) (10’) • Program design (20’)
Key Concepts • OOP • Entity, Object, Class • State/property: data field / variable • Behavior: function • Immutable Classes/Objects • Static Members • Destructors • Copy Constructor • Friend Functions/Classes
Defining Class • Constructor • Name and return value! • Called by the system NOT you! • Default constructor: unavailable if?? • Initialization of variables • Declaration + Implementation • Inline declaration
Creating objects • With/without arguments • Anonymous objects • Array of objects • Object data field • Initializer
Access Object • Access members by • Object name • Object pointer • “this” pointer • Memberwise copy • Data encapsulation • Accessibility keyword • Getter and setter
Immutable Class • The object that cannot be changed after creation Define data fields as private Don’t provide mutators No accessor functions that return a reference/pointer to a mutable member!
Static Members Can a static function call an instance function? • Concepts • Instance(实例) • Instance variable/function vs. static variable/function • To declare: static type var_name;//In declaration static type functionName(parameters){} • To initialize: type ClassName::var_name = 0; //re-declare it with initial value in implementation • To access/call: (ClassName::)var_name… ClassName::functionName(arguments);
Constant Member Functions class Point{public:int GetX() const;int GetY() const;void SetPt (int, int);void OffsetPt (int, int);private:int xVal, yVal;}; --The function that won’t change the object’s data members. --Part of the function signature! --Overloading?
Destructors • Concept • Opposite of constructor • ~Circle() { • numberOfObjects--; • } • Notes: • No return value, no parameters • So, no overloading • A default destructor is available if • No destructor is explicitly defined • A destructor is useful if some resource, e.g. memory is allocated dynamically by an object
Copy Constructor ClassName(ClassName &); Explicit object initialization Copy of temporary object for parameter Copy of temporary object for return value • Shallow Copy vs. Deep Copy
Friendship • Friend function • Friend class • class Name{ • … • friend class FriendName; • friend type funcName(); • … • }; Where to declare? In “public” or “private” part. Where to implement? Inside or outside the definition of the class
Key Concepts • Inheritance • Function redefining, function overloading • Polymorphism • Virtual function, abstract function, abstract class • Dynamic casting
Class Inheritance • Syntax: B 基类 父类 超类 Base Parent Super-Class 派生类 子类 Derived-Class Child A class DerivedClass : acckeyword BaseClass{…}; class A: public B{ public: … private: … }; A B
Constructor/Destructor in Inheritance • The constructors of a base class are not inherited • Calling base class constructors • No-Arg Constructor in Base Class • Constructor and Destructor Chaining Circle::Circle(double radius, string color, bool filled) :GeometricObject(color, filled) { this->radius = radius; } class A: public B{ … }; class ME: public A, public C{ ... D d; }; Invoking order of constructors: B, A, C, D, ME Invoking order of destructors: in reverse order
Redefining vs. Overloading circle1.GeometricObject::toString();
Polymorphism Human Chinese Cantonese • Dynamic binding • Counterpart: static binding • Two elements • Virtual function • Pointer of base class Polymorphism (多态) int main(){ HM * hm = new HM(); hm->show(); delete hm; hm = new CN(); hm->show(); delete hm; hm = new CT(); hm->show(); delete hm; } Upcasting and Downcasting
Virtual Function • If a function is defined virtual in a base class, it is automaticallyvirtual in all its derived classes class C { public: virtual string toString() { return "class C"; } }; class B: public C { string toString() { return "class B"; } };
Abstract Class and Abstract Function • Abstract function: pure virtual function • Abstract class: a class with abstract functions virtual double getArea() = 0; virtual double getPerimeter() = 0; Why we need it?
Key Concepts • Operator function • Operator overloading • As member • As friend
Overloading as Member A member function of Rational class. Parameter: usually pass-by-reference (can by value) one for a binary operator (The other one the object of the function) keyword bool Rational::operator< (Rational &secondRational){ long n = numerator * secondRational.getDenominator() – denominator * secondRational.getNumerator(); if (n < 0) return true; elsereturn false; } Rational Rational::operator+(Rational &secondRational){ returnthis->add(secondRational); }
Notes • The left operand is fixed to be the operating object automatically c1 = c2 + c3 ; c1 = c2.operator+(c3); • The number of parameters is determined by the operator itself • You cannot change it • Overloading does not change the operator precedence (优先级) and associativity (结合性) • The (return) type of the operator function can be defined by you • Usually the same class type to be operational in complex operation
Overloading ++ and -- • Rational Rational::operator++() { • numerator += denominator; • return *this; • } r1++ ++r1 • Rational Rational::operator++(){ • Rational temp(numerator, denominator); • numerator += denominator; • return temp; • } (int dummy){ 哑元参数,the value is never used; It must be “int”.
Overloading as Friend friend ostream &operator<<(ostream &, Rational &); friend istream &operator>>(istream &, Rational &); ostream &operator<<(ostream &str, Rational &rational){ str << rational.numerator << " / " << rational.denominator; return str; } Other operators can also be overloaded as friends!
Object Conversion Rational::operator double() { return1.0 * getNumerator() / getDenominator(); } Rational r1(1, 4); double d = r1 + 5.1; cout << "r1 + 5.1 is " << d << endl;
Key Concepts • Exception • Naive Exception Handling • C++ Exception Handling • Exception Classes: standard vs. custom • Throw list
Template for try-throw-catch The rest code may NOT be executed! try { Code to try; throw …; More code to try; }catch (type1 e1){ Code to process the exception; }catch(type2 e2){ Code to process the exception; throw; } int quotient(int num1, int num2){ if (num2 == 0) throw num1; return num1 / num2; } int main(){ //… try{ int result = quotient(num1, num2); //… } catch (int){ //… } //… } ? Multiple catches. The order? Advantages of C++ Exception Handling? When to use it?
Exception Specification • throw list • No throw list • Empty throw list returnType functionName(parameterList) throw (exceptionList); returnType functionName(parameterList); returnType functionName(parameterList) throw (); Undeclared Exceptions?
Key Concepts • Function template • Class template
Function Template template <typename T1, typename T2, typename T3> T1 funTemp<T1 v1, T2 v2, T3 v3>{ … } template <typename T1, typename T2, typename T3> T1 funTemp<T1 v1, T2 v2>{ … T3 a; … }
Function Template Overloading (a) template <class TYPE> TYPE max(TYPE x, TYPE y); Sequence of matching: (1)The common function with matching parameter list (no type conversion); (2)The matching function template (no type conversion); (3)The common function with matching parameter list after implicit type conversion; (4) Otherwise, compiling error. (b) template <class TYPE> TYPE max(TYPE x, TYPE y, TYPE z); (c) template <class TYPE> TYPE max(TYPE x[], int n); (d) double max(int x, double y); Example: max(1, 1.2); max(2, 3); max(3, 4, 5); Example: max(array1, 5); max(2.1, 4.5) max(‘B’, 9)
Class Template template<typename T=int , int cpty> class Stack{ public: Stack(); bool empty(); T peek(); T push(T value); T pop(); int getSize(); private: T elements[cpt]; int size; }; template<typename T> Stack<T>::Stack(){ size = 0; } template<typename T> T Stack<T>::push(T value){ return elements[size++] = value; } template<typename T> T Stack<T>::pop(){ return elements[--size]; }
Template and Inheritance template<typename str> class Node{/* … */};template<typename thestr> class Element : public Node<thestr>{/* … */}; Nontemplate class (Common class) Class template class Set : publicNode<int>{/* … */}; Specialization
Key Concepts • STL • STL iterator • STL container • Three types • STL algorithm Need to know --Definitions --Features
File Opening and Closing • “ifstream”, “ofstream”, “fstream” • open() and close() • File name • Absolute path • Relative path • File open modes • ios:in, ios::out, ios::binary, … • Combinations • Testing stream status • eof(), fail(), bad(), good(), clear()
Text File I/O • “<<“, “>>” • get(), put() • getline()
Binary File I/O • Binary file vs. text file • read(), write() • Type casting: reinterpret_cast • Random access • File pointers • ios::beg, ios::end, ios::cur • seekp(), seekg()
That’s all! Question & Answer Session: 2:30~5:00pm, Jun 16 (Thu) Room: Lab 401 Good Luck!