Вы находитесь на странице: 1из 18

Example 1

class Name { public: Name(void) { myName = 0; } ~Name(void) { delete[] myName; } void SetName(char* n) { myName = new char[strlen(n)+1]; strcpy(myName,n); } void Print(void) { cout << myName << endl; } private: }; class Contact: public Name { public: Contact(void) { myAddress = 0; } ~Contact(void) { delete[] myAddress; } void SetAddress(char* c) { myAddress = new char[strlen(c)+1]; strcpy(myAddress,c); } void Print(void) { Name::Print(); cout << myAddress << endl; } private: }; char* myAddress; char* myName;

int main(void) { Contact c; c.SetName("John McClane"); c.SetAddress("137th floor, Nakatome Towers"); } c.Print();

*************************************************** * Example 2 showing the use of string functions * *************************************************** #include <iostream.h> #include <conio.h> #include <string.h> const int MAXLENGTH = 500; // define maximum string length void main() { char FirstName[20] = "Donald"; char LastName[20] = "Duck"; char FullName[MAXLENGTH+1]; // function strlen gives the length of a string if (strlen(FirstName) + strlen(LastName) > MAXLENGTH) { cout << "\nName too long"; return 1; } strcpy (FullName, FirstName); // copy string strcat (FullName, " "); // add space to end of string strcat (FullName, LastName); // add last name cout << "\nThe full name is " << FullName; // compare strings. The function stricmp returns 0 if the strings are equal if (stricmp(FirstName,LastName) == 0) { cout << "\nFirst and last name are identical"; } getch(); } /************************* ************************************** Example 3 * The hospital in Software City has three departments: heart clinic, lung * * clinic, and plastic surgery. The head nurse keeps three lists of patients * * waiting for an operation, one for each department. Each new patient * * normally comes last in the queue, but critically ill patients and patients * * who bribe the chief surgeon come first in the queue. Some patients die * * while waiting for an operation. This program keeps track of the three * * patient queues. * * * * A structure called patient holds all information for one patient. * * A class called queue encapsulates a patient queue for one department, * * implemented as a linked list. Patient records are created dynamically. * ****************************************************************** #include <iostream.h> #include <conio.h> #include <string.h> #include <stdlib.h>

// define maximum number of patients in a queue #define MAXPATIENTS 100 // define structure for patient data struct patient { patient * next; char FirstName[50]; char LastName[50]; char ID[20]; }; // define class for queue class queue { public: queue (void); ~queue (void); int AddPatientAtEnd (patient * p); int AddPatientAtBeginning (patient * p); patient * GetNextPatient (void); patient * RemoveDeadPatient (patient * p); void OutputList (void); char DepartmentName[50]; private: patient * List[MAXPATIENTS]; patient * first, * last; }; // declare member functions for queue queue::queue () { // constructor first = last = NULL;} queue::~queue () { // destructor patient * p1, * p2; for (p1=first; p1; ) { p2 = p1; p1 = p1->next; delete p2;}} int queue::AddPatientAtEnd (patient * p) { // adds a normal patient to the end of the queue. // returns 1 if successful, 0 if queue is full. if (p == NULL) { // memory is full return 0;} // put in new patient if (first) { last->next = p; last = p;} else {

// queue is empty first = last = p;} p->next = NULL; return 1;} int queue::AddPatientAtBeginning (patient * p) { // adds a critically ill patient to the beginning of the queue. // returns 1 if successful, 0 if queue is full. if (p == NULL) { // memory is full return 0;} // put in new patient if (first) { p->next = first; first = p;} else { // queue is empty first = last = p; p->next = NULL;} return 1;} patient * queue::GetNextPatient (void) { // gets the patient that is first in the queue. // returns NULL if queue is empty patient * p; if (first) { p = first; first = first->next;} else { // queue is empty p = NULL;} return p;} patient * queue::RemoveDeadPatient (patient * p) { // removes a patient from queue. // returns patient if found or NULL if not found patient * p1, * p2 = NULL; // search for patient for (p1=first; p1; p1 = p1->next) { if (stricmp(p1->ID, p->ID) == 0) { // patient found in queue // remove from queue if (p1 == first) { // adjust first first = first->next;} if (p1 == last) { // adjust last last = p2;} if (p2) { // adjust pointer in previous record

p2->next = p1->next;} return p1;} // remember previous record p2 = p1;} // not found return NULL;} void queue::OutputList (void) { // lists entire queue on screen patient * temp; if (first) { for (temp=first; temp; temp = temp->next) { cout << "\n" << temp->FirstName; cout << " " << temp->LastName; cout << " " << temp->ID;}} else { // queue empty cout << "\n\nQueue is empty";}} // declare functions used by main: patient * InputPatient (void) { // this function asks user for patient data. // create new patient record patient * p = new patient; // enter data into record cout << "\n\nPlease enter data for new patient\nFirst name: "; cin.getline(p->FirstName, sizeof(p->FirstName)); cout << "\nLast name: "; cin.getline(p->LastName, sizeof(p->LastName)); cout << "\nSocial security number: "; cin.getline(p->ID, sizeof(p->ID)); // check if data valid if (p->FirstName[0]==0 || p->LastName[0]==0 || p->ID[0]==0) { // rejected delete p; p = NULL; cout << "\n\nError: Data not valid. Operation cancelled."; getch();} return p;} void OutputPatient (patient * p) { // this function outputs patient data to the screen if (p == NULL) { cout << "\nNo patient"; return;} cout << "\n\nPatient data:"; cout << "\n\nFirst name: " << p->FirstName; cout << "\n\nLast name: " << p->LastName; cout << "\n\nSocial security number: " << p->ID;}

int ReadNumber() { // this function reads an integer number from the keyboard. // it is used because input with cin >> doesn't work properly! char buffer[20]; cin.getline(buffer, sizeof(buffer)); return atoi(buffer);} void DepartmentMenu (queue * q) { // this function defines the user interface with menu for one department int choise = 0, success; patient * p, * p1; while (choise != 6) { // clear screen clrscr(); // print menu cout << "\n\n\nWelcome to department: " << q->DepartmentName; cout << "\n\nPlease enter your choise:"; cout << "\n\n1: Add normal patient"; cout << "\n2: Add critically ill patient"; cout << "\n3: Take out patient for operation"; cout << "\n4: Remove dead patient from queue"; cout << "\n5: List queue"; cout << "\n6: Change department or exit\n"; // get user choise choise = ReadNumber(); // do indicated action switch (choise) { case 1: // Add normal patient p = InputPatient(); if (p) { success = q->AddPatientAtEnd(p); clrscr(); if (success) { cout << "\nPatient added:\n\n"; OutputPatient(p);} else { // error cout << "\n\nError: The queue is full. Cannot add patient:"; OutputPatient(p); delete p;} cout << "\n\nPress any key"; getch();} break; case 2: // Add critically ill patient p = InputPatient(); if (p) { success = q->AddPatientAtBeginning(p); clrscr(); if (success) { cout << "\nPatient added:\n\n";

OutputPatient(p);} else { // error cout << "\n\nError: The queue is full. Cannot add patient:"; OutputPatient(p); delete p;} cout << "\n\nPress any key"; getch();} break; case 3: // Take out patient for operation p = q->GetNextPatient(); clrscr(); if (p) { cout << "\nPatient to operate:\n\n"; OutputPatient(p); // delete patient record delete p;} else { cout << "\nThere is no patient to operate.";} cout << "\n\nPress any key"; getch(); break; case 4: // Remove dead patient from queue p = InputPatient(); if (p) { p1 = q->RemoveDeadPatient(p); clrscr(); if (p1) { cout << "\nPatient removed:\n\n"; delete p;} else { // error cout << "\n\nError: Cannot find patient:\n\n"; p1 = p;} OutputPatient(p1); delete p1; cout << "\n\nPress any key"; getch();} break; case 5: // List queue clrscr(); q->OutputList(); cout << "\n\nPress any key"; getch(); break; }}} // main function defining queues and main menu void main () { int i, MenuChoise = 0; // define three queues

queue departments[3]; // set department names strcpy (departments[0].DepartmentName, "Heart clinic"); strcpy (departments[1].DepartmentName, "Lung clinic"); strcpy (departments[2].DepartmentName, "Plastic surgery"); while (MenuChoise != 4) { // clear screen clrscr(); // print menu cout << "\n\n\nWelcome to Software City Hospital"; cout << "\n\nPlease enter your choise:\n"; for (i = 0; i < 3; i++) { // write menu item for department i cout << "\n" << (i+1) << ": " << departments[i].DepartmentName;} cout << "\n4: Exit\n"; // get user choise MenuChoise = ReadNumber(); // is it a department name? if (MenuChoise >= 1 && MenuChoise <= 3) { // call submenu for department // (using pointer arithmetics here:) DepartmentMenu (departments + (MenuChoise-1));}}}
Example 4 Array // // * runtime memory allocation for an array with new * amount of memory allocated depends on program state

#include <iostream> using namespace std; int main() { int *a ; // declares that a[0]...a[something] will be array, // but doesn't allocate any memory for it int N ; do { cout << "enter vector length: " ; cin >> N ; } while ( N < 1 ) ; a = new int[N] ; // allocates the memory for a[0]..a[N-1] if(!a) { cout << "Memory allocation failed\n" ; return -1 ; } // Read in the vector from stdin for ( int n = 0 ; n < N ; n ++ ) { cout << "a[" << n << "]: " ; cin >> a[n] ; }

// print out the vector for ( int n = 0 ; n < N ; n ++ ) { cout << "a[" << n << "] = " ; cout << a[n] ; cout << endl;

}
// free the memory delete [] a ; // The '[]' indicate that // what's being freed is an array return 0; }

Example 5
// DateClass // Program to demonstrate the definition of a simple class // and member functions #include <iostream> using namespace std; // Declaration of Date class class Date { public: Date(int, int, int); void set(int, int, int); void print(); private: int year; int month; int day; }; int main() { // Declare today to be object of class Date // Values are automatically intialised by calling constructor function Date today(1,9,1999); cout << "This program was written on "; today.print(); cout << "This program was modified on "; today.set(5,10,1999); today.print(); } return 0;

// Date constructor function definition Date::Date(int d, int m, int y) { if(d>0 && d<31) day = d; if(m>0 && m<13) month = m; if(y>0) year =y;

} // Date member function definitions void Date::set(int d, int m, int y) { if(d>0 && d<31) day = d; if(m>0 && m<13) month = m; if(y>0) year =y; } void Date::print() { cout << day << "-" << month << "-" << year << endl;

} Class Inheritance
class Circle { public: Circle(); void setRadius(double r); double getRadius(); double Diameter(); double Circumference(); double Area(); void Display(); protected: double Radius; private: }; const double PI = 3.14159; Circle::Circle() { Radius = 0;}

void Circle::setRadius(double r) { Radius = r <= 0 ? 1 : r;}

double Circle::getRadius() { return Radius;}

double Circle::Diameter() {return Radius * 2;} double Circle::Circumference() { return Diameter() * PI;}

double Circle::Area()

{ return Radius * Radius * PI; } void Circle::Display() { cout << "\nCircle Properties"; cout << "\nRadius cout << "\nDiameter = " << getRadius(); = " << Diameter();

cout << "\nCircumference = " << Circumference(); cout << "\nArea } struct Sphere : public Circle {public: double Volume(); void Show(); private: }; double Sphere::Volume() { return Radius * Radius * Radius * PI * 4 / 3; } void Sphere::Show() { cout << "\nCircle Properties"; cout << "\nRadius cout << "\nDiameter = " << getRadius(); = " << Diameter(); = " << Area() << "\n";

cout << "\nCircumference = " << Circumference(); cout << "\nArea cout << "\nVolume } void main() { Circle circle; circle.Display(); // Displaying a circle using the default value of the radius = " << Area(); = " << Volume() << "\n\n";

Circle circ; circ.setRadius(12.50); circ.Display();

// A circle with a value supplied for the radius

Sphere sphere;

// A sphere that has its own radius, using the functions

sphere.setRadius(8.95); // of the base class sphere.Show();

*************************************** * Example 5 showing how to use 2-dimensional arrays with functions * This program multiplies all elements in a matrix with a factor (scalar). * * * * The program has the following sub-functions: * * ReadMatrix: reads matrix from keyboard input, * * WriteMatrix: writes matrix to screen, * * MultiplyByScalar: multiplies matrix by scalar. * * * * Note that when a function parameter is declared as an array, you actually * * get a pointer, not a copy of the array. This means that you can modify * * the array inside the function and the change has effect on the original * * array outside the function. * * * ******************************************************************************/ #include <iostream.h> #include <iomanip.h> #include <conio.h> const int rows = 3; // number of rows in matrix (must be constant) const int columns = 3; // number of columns in matrix (must be constant) void ReadMatrix (float ma[rows][columns]) // this function reads matrix from keyboard { int r, c; cout << "\nPlease enter matrix"; for (r=0; r<rows; r++) { for (c=0; c<columns; c++) { cout << "\nElement A(" << (r+1) << "," << (c+1) << ") "; cin >> ma[r][c]; } } } void WriteMatrix (float ma[rows][columns]) // this function writes matrix on screen { int r, c; cout << "\nMatrix is:"; for (r=0; r<rows; r++) { cout << "\n"; for (c=0; c<columns; c++) { // setw(10) adds space to make all numbers 10 characters wide cout << setw(10) << ma[r][c] << " "; } }

} void MultiplyByScalar (float sq[rows][columns], float fac) // this function multiplies a matrix by a scalar { int i, j; for (i=0; i<rows; i++) { for (j=0; j<columns; j++) { sq[i][j] = sq[i][j] * fac; } } } void main () { // declare matrix and scalar float A[rows][columns], f; // get matrix from user ReadMatrix(A); // get scalar from user cout << "\n\nEnter factor "; cin >> f; // multiply matrix by scalar MultiplyByScalar (A, f); // output result matrix on screen WriteMatrix(A); // wait for user to press a key getch(); } Derived Classes 1
// Using base pointers on derived class objects. #include <iostream> #include <cstring> // for older compilers, use <string.h> using namespace std; class B_class { char author[80]; public: void put_author(char *s) { strcpy(author, s); } void show_author() { cout << author << "\n"; } } ; class D_class : public B_class { char title[80]; public: void put_title(char *num) { strcpy(title, num); } void show_title() { cout << "Title: ";

} };

cout <<

title << "\n";

int main() { B_class *p; B_class B_ob; D_class *dp; D_class D_ob; p = &B_ob; // address of base

// Access B_class via pointer. p->put_author("Tom Clancy"); // Access D_class via base pointer. p = &D_ob; p->put_author("William Shakespeare"); // Show that each author went into proper object. B_ob.show_author(); D_ob.show_author(); cout << "\n"; /* Since put_title() and show_title() are not part of the base class, they are not accessible via the base pointer p and must be accessed either directly, or, as shown here, through a pointer to the derived type. */ dp = &D_ob; dp->put_title("The Tempest"); p->show_author(); // either p or dp can be used here. dp->show_title( ); return 0;}

2
#include <iostream> using namespace std; class road_vehicle { int wheels; int passengers; public: void set_wheels(int num) { wheels = num; } int get_wheels() { return wheels; } void set_pass(int num) { passengers = num; } int get_pass() { return passengers; } }; class truck : public road_vehicle { int cargo; public: void set_cargo(int size) { cargo = size; } int get_cargo() { return cargo; } void show(); }; enum type {car, van, wagon};

class automobile : public road_vehicle { enum type car_type; public: void set_type(type t) { car_type = t; } enum type get_type() { return car_type; } void show(); }; void truck::show() { cout << "wheels: " << get_wheels() << "\n"; cout << "passengers: " << get_pass() << "\n"; cout << "cargo capacity in cubic feet: " << cargo << "\n"; } void automobile::show() { cout << "wheels: " << get_wheels() << "\n"; cout << "passengers: " << get_pass() << "\n"; cout << "type: "; switch(get_type()) { case van: cout << "van\n"; break; case car: cout << "car\n"; break; case wagon: cout << "wagon\n"; } } int main() { truck t1, t2; automobile c; t1.set_wheels(18); t1.set_pass(2); t1.set_cargo(3200); t2.set_wheels(6); t2.set_pass(3); t2.set_cargo(1200); t1.show(); t2.show(); c.set_wheels(4); c.set_pass(6); c.set_type(van); c.show(); } 3 return 0;

#include <iostream> class base { int i; protected: int j; public: int k;

void seti(int a) { i = a; } int geti() { return i; } }; // Inherit base as protected. class derived : protected base { public: void setj(int a) { j = a; } // j is protected here void setk(int a) { k = a; } // k is also protected int getj() { return j; } int getk() { return k; } }; int main() { derived ob; /* This next line is illegal because seti() is a protected member of derived, which makes it inaccessible outside of derived. */ // ob.seti(10); // // cout << ob.geti(); // illegal -- geti() is protected ob.k = 10; // also illegal because k is protected // these next statements are OK ob.setk(10); cout << ob.getk() << ' '; ob.setj(12); cout << ob.getj() << ' '; return 0; }

Exercises Matrix operations


Write a program that can do the following: addition of two matrices subtraction of two matrices multiplication of a matrix by a scalar multiplication of a matrix by a matrix transpose a matrix

The order of the matrices could be 3 x 3, or variable if you want.

Telephone directory Make a program that can sort a list of names and telephone numbers alphabetically. Persons are sorted alphabetically by their last names. Persons with the same last name are sorted by their first names. Input: names and telephone numbers, Output: list of names and telephone numbers ordered alphabetically. Define a structure named person that contains a person's first name, last name, and telephone number. Define a function that compares two structures of type person according to the following prototype: int compare(person * a, person * b); This function should return a negative value if person a comes before b, and a positive value if b comes before a. (You may use the function stricmp(name1,name2) to compare two strings). Define a function that swaps the contents of two structures of type person: void swap(person * x, person * y); Use the following function to sort an array of structures of type person: void sort(person * list, int NumberOfPersons)

Parabola as object Make a class defining a polynomial of second degree y = A x2 + B x + C The coefficients A, B, C should be private. The class should contain the following member functions: a function that sets the coefficients to desired values a function that calculates y for a given value of x a function that tells how many roots there are and returns the roots (if any) a function that tells whether the polynomial has a maximum, a minimum, or no extremum, and gives x and y for the extremum (if any)

Make a program to test an object of this class.

In case you've forgotten everything you've learned in math, here are the formulae:

Discriminant

Animal insurance

Write a program that prints the insurance fee to pay for a pet according to the following rules: A dog that has been neutered costs $50. A dog that has not been neutered costs $80. A cat that has been neutered costs $40. A cat that has not been neutered costs $60. A bird or reptile costs nothing. Any other animal generates an error message.

The program should prompt the user for the appropriate information, using a code to determine the kind of animal (i.e. D or d represents a dog, C or c represents a cat, B or b represents a bird, R or r represents a reptile, and anything else represents some other kind of animal). After printing the insurance fee, the program should ask the user if he wants to insure another animaI.

Вам также может понравиться