Fundamentals of Programming
Lecture 11 Hamed Rasifard
1
Fundamentals of Programming Lecture 11 Hamed Rasifard 1 Outline - - PowerPoint PPT Presentation
Fundamentals of Programming Lecture 11 Hamed Rasifard 1 Outline Enumerations C++ 2 Enumerations An enumeration is a set of named integer constants. Enumerations are defined much like structures; the keyword enum signals the
Lecture 11 Hamed Rasifard
1
2
3
enum tag { enumeration list };
4
#include <stdio.h> enum coin { penny, nickel, dime, quarter, half_dollar, dollar}; int main( void ) { enum coin money; money = dime; switch(money) { case penny: printf("penny"); break; case nickel: printf("nickel"); break; case dime: printf("dime"); break; case quarter: printf("quarter"); break; case half_dollar: printf(''half_dollar"); break; case dollar: printf("dollar"); } return 0; }
5
6
around its code (what is happening) around its data (who is being affected)
programs are typically organized around code.
data, with the key principle being "data controlling access to code."
7
#include <iostream> using namespace std; int main() { int i; cout << "This is output.\n"; // this is a single line comment /* you can still use C style comments */ // input a number using >> cout << "Enter a number: "; cin >> i; // now, output a number using << cout << i << " squared is " << i*i << "\n"; return 0; }
8
9
10
names of identifiers to avoid name collisions.
separate from elements declared in another.
program, the contents of that header are contained in the std namespace.
11
12
class class-name { private data and functions access-specifier: data and functions access-specifier: data and functions // ... access-specifier: data and functions } object-list;
13
Private Public Protected
14
#define SIZE 100 // This creates the class stack. class stack { int stck[SIZE]; int tos; public: void init(); void push(int i); int pop(); }; void stack::init() { //Code goes here } void stack::push(int i) { //Code goes here } int stack::pop() { //Code goes here }
15
16
#include <iostream> using namespace std; #define SIZE 100 // This creates the class stack. class stack { . . . }; . . . int main() { stack stack1, stack2; // create two stack objects stack1.init(); stack2.init(); stack1.push(1); stack2.push(2); stack1.push(3); stack2.push(4); cout << stack1.pop() << " "; cout << stack1.pop() << " "; cout << stack2.pop() << " "; cout << stack2.pop() << "\n"; return 0; }
17
initialization for class objects is inelegant and error- prone.
declare a function with the explicit purpose of initializing objects.
type, it is called a constructor.
name as the class itself.
18
class will be initialized.
arguments must be supplied
class Date{ int y, m, d; public: //... Date(int, int, int); // day, month, year Date(int, int); // day, month, today’s year Date(int); // day today’s month and year Date(); // default Date: today Date(const char*); // date in string representation };