c4ab969c9e924244ef5f4202150960db.ppt
- Количество слайдов: 20
C++ Overview (I) What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that take into account code and data; organise subgroups into hierarchy; translate to objects… Objects o Encapsulation: combine together code and data: data-hiding o Polymorphism: same interface, different ways of calling o Inheritance: derive specific objects from more general ones An object is defined by a class; the class combines data and methods; a class defines a new data type… think in objects!
C++ Overview (II) Function overloading A function can represent a concept (e. g. set_value) but it may be called with different types of data – the compiler sorts out which variant of set_value to call Operator overloading Any of the operators in C++ (e. g. ‘+’) can be redefined; a class can define how ‘+’ operates on objects defined by the class Inheritance For a group of related concepts (e. g. types of buildings) extract common functionality and data into a base class (e. g. building) and derive more specific classes (e. g. house, garage, hotel)
C++ Classes (I) In general, a class is declared in a header file and defined in a source file; #include the header file wherever the class is used in file “andy. h” class Andy { private: int age; Name of class and new data type Until otherwise specified, declarations can only be accessed by methods of class ‘Andy’ public: Specify that declarations can be accessed Andy(); by any part of the program ~Andy(); void set. Age(int); int get. Age(); A function that returns an integer: }; a method of class ‘Andy’ Note the semi-colon
Classes (II) In file “andy. cpp” Andy: : Andy() { age = 0; } Andy: : ~Andy() { } C++ Constructor function: called whenever an object of type ‘Andy’ is initialised Destructor function: called whenever an ‘Andy’ object goes out of scope (or is deleted) void Andy: : set. Age(int _age) { ‘age’ is a private member of class ‘Andy’ age = _age; so must be accessed by a class method } int Andy: : get. Age() { return age; } ‘: : ’ is the scope operator; need to tell the compiler we are defining ‘get. Age’ in class ‘Andy’ – no ‘: : ’ means function is not a class method
in file ‘main. cpp’ #include <iostream. h> #include “andy. h”. . Andy andy 1, andy 2; Andy* andy. Ptr = 0; Classes (III) C++ Variables are declared in just the same way as if they were, say, integers andy 1. set. Age(1); andy 2. set. Age(99); Call methods on objects using the ‘. ’ operator (just like structs) andy. Ptr = &andy 2; cout << << <<. . “Andy is aged “ andy 1. get. Age() “ or “ andy. Ptr->get. Age() “n”; Call methods through a pointer to an object by using ‘->’ operator; just like with structs
C++ Classes (IV) Construction and Destruction Can have many different forms of constructor Constructor and destructor do NOT return a value Good practice to supply an empty constructor Andy(); Andy(int); Andy(char*, int); Object Assignment and passing to functions The compiler automatically does a bitwise copy if an object is assigned (‘=‘) to another object or used as an argument to a function – can override the automatic behaviour… Andy a, b; void func(Andy aaa); a. set. Age(10); b = a; cout << b. get. Age(); Andy a; func(a);
C++ Arrays of objects (I) in file ‘element. h’ class Element { private: double u, v; public: double result; Two constructors: one is the ‘empty’ or ‘default’ and the other takes two values used to initialise private members Element() : u(0. 0), v(0. 0) {} Element(double _u, double _v) : u(_u), v(_v) {} double length() { return sqrt(u*u + v*v); } }; Function (aka method) defined in header file: called an ‘inline’ function
C++ Arrays of objects (II) int j; Element* elem = new Element[100]; for (j=0; j<100; j++) { elem[j] = Element(1. 0, 0. 5); } for (j=0; j<100; j++) { double len = elem[j]. length(); double res = elem[j]. result; } Element* ptr = elem; for (j=0; j<100; j++) { double len = ptr->length(); elem++; } Make new copy of elem[j] by assignment from Element constructed with initial values Call ‘length’ method Access public ‘result’ variable Call ‘length’ method thru pointer
C++ Overloading (I) o One function/method can take many forms o Overloaded functions must all return same type of value o Compiler decides which form of function to call class Andy { private: double d. Val; float f. Val; int i. Val; public: void set. Data(double val) { d. Val = val; } void set. Data(float val) { f. Val = val; } void set. Data(int val) { i. Val = val; } }; Andy a; a. set. Data(1. 0 f); a. set. Data(42);
C++ Overloading (II) o Overloading operators can change their meaning o Can overload any operator o Makes for easy to read code Class Vector { private: double a, b; public: Vector() : a(0. 0), b(0. 0) {} Vector(double _a, double _b) : a(_a), b(_b) {} Vector operator+(Vector x) { return Vector(a+x. a, b+x. b); } }; Vector u(2. 0, -2. 0), v(-1. 0, 1. 0), w; w = u + v; ‘+’ operator method of u is called with v as the function argument
C++ Inheritance (I) o One class can inherit the public data and methods of another o Can build complexity thru using a hierarchy o Can access specialised classes thru a pointer to the base class For instance, a square, a cross and a triangle are all shapes; they can all be represented using differing numbers of vertices Create a base class called shape and derive different types class Shape { public: int nvertex; Vertex* vertices; Shape(int, Vertex*); virtual draw(); }; Data to represent any of the different shape types Base class constructor ‘virtual’ function is inherited
Inheritance (II) C++ class Square : public Shape { public: Square(Vertex* _v) : Shape(4, _v) {} void draw(); }; Call the base class constructor before constructing ‘Square’ void Square: : draw() { // draw a line loop thru all vertices } class Cross : public Shape { Explicit drawing methods: public: Triangle(Vertex* _v) : Shape(4, _v) {} different from each other void draw(); }; void Cross: : draw() { // draw 2 lines, connecting opposite vertices }
Inheritance (III) C++ . . // declare the Vertex data for each type of shape. . Array of pointers to base class Shape* shapes[4]; shapes[0] shapes[1] shapes[2] shapes[3] = = new new Cross(cross. Data); Square(square. Data); Triangle(triangle. Data); Hexagon(hexagon. Data); for (int j=0; j<4; j++) { Shape* ptr = shapes[j]; ptr->draw(); }. . ‘new’ operator allocates memory for object and returns pointer to it; pointer to ‘Cross’ is also a pointer to ‘Shape’ The compiler works out which ‘draw’ function to call Example: shape
C++ Template classes o Templates are generic classes that offer particular functionality o They ‘wrap’ around other classes o Standard template classes are available #include <list. h>. . list<int> list. Of. Ints; list. Of. Ints. push_back(4); . . list. Of. Ints. sort(); Header file from standard libraries Specify what we want a list of Add something to the list ‘list’ class uses ‘<‘ and ‘>’ operators of ‘int’ to order the list<int>: : iterator iter; for (iter=list. Of. Ints. begin(); iter!=list. Of. Ints. end(); iter++) { if (*iter == 4) { cout << “found it!n”; Processing thru the list } }
C++ Array based I/O Frequently need to write variables into a character string #include <strstrea. h> #include <fstream. h> char cstring[80]; int filenumber = 11; ostrstream ostr(cstring, 80); ostr << << “datafile” filenumber “. dat” ends; ostrstream object uses cstring as a buffer Write into ‘ostr’ in the same way as to the screen or to a file ‘ends’ adds a ‘ ’ to the end of the C string // now can use cstring to open a file ofstream ofile; ofile. open(cstring); // opens a file named “datafile 11. dat”
C++ Standard Libraries Some slight confusion, courtesy of Microsoft (? ) #include <fstream. h> You are allowed to use this type of header (*. h) sometimes Main standard header files are: #include <fstream> using namespace std; You should use this type, but need to add the ‘using’ line after one or more includes <cmath> = <math. h> <algorithm>, <climits>, <cmath>, <cstdlib>, <fstream>, <iostream>, <list>, <string>, <strstream> There are lots more: see “Library, Standard C++” in MSDN index You can include C headers (and use C functions) in C++ programs
The ‘string’ class C++ o The standard string class is very useful; saves a lot of work o Many (library) functions require C strings (char*) o The string class can be used to manipulate and create C strings #include <string> using namespace std; . . string s 1(“C++ is my friend”); string s 2 = “Andy”; string s 3; s 3 = s 2 + “, “ + s 1; char* cs 1 = s 3. c_str(); . . Other methods of class string include finding sub-strings, getting string length, ==, <, >, != and lots more… See “string” and “basic_string” in the MSDN documentation
Worked example: ‘finite’ (I) ‘this’ element Neighbour C++ 1) Create grid of elements dymanically 2) Initialise elements – random values 3) For each timestep: Each element interacts mathematically with its 4 neighbours to find a result Output result from each element 4) Destroy memory used Classes required: o Grid (to contain and process elements) o Element (to store result and data) o Index (to help find neighbours) This element stores the addresses of its neighbouring elements
C++ Worked example: ‘finite’ (II) class Element { private: double u, v; Element* left. Elem. Ptr; Element* right. Elem. Ptr; Element* above. Elem. Ptr; Element* below. Elem. Ptr; public: double result; Some data Pointer to neighbour Result can be accessed directly Element(); ~Element() {} void add. Neighbours(Element*, Element*); void init(double, double); Set ‘u’ and ‘v’ values void update(); void normalise(); double length(); This method does the double sum. Of. Parts(); }; (daft) computation
C++ The End C++ Fortran The only way to learn a computer programming language is to program in it
c4ab969c9e924244ef5f4202150960db.ppt