C++ ReviewEECE 3521 EECS 352 Data Structures and Algorithms José M. Vidal Office: 3A47
C++ ReviewEECE 3522 C++ Review Data types Input/Output Classes –Data abstraction (public/private) –Constructors/Destructors –Operator Overloading –Inheritance
C++ ReviewEECE 3523 C++ Data Types char1 byte short2 bytes int4 bytes long4 bytes float4 bytes double8 bytes bool 1 byte Signed and unsigned keywords can be used with char, short, int and long. Variations are possible: long double, long long, signed char, unsigned long...
C++ ReviewEECE 3524 Output #include Tell compiler that we are doing I/O cout Object to which we can send data. << Device for sending data. endl `\n’ `\t’ Special symbols that we can send.
C++ ReviewEECE 3525 Formatting Output ios::left left justify the output ios::right right justify the output ios::scientific use scientific notation for numbers ios::hex print numbers in hexadecimal base ios::dec print numbers in decimal base ios::uppercase print all characters in upper case cout.setf(long flag)cout.unsetf(long flag) Set different formatting parameters for next output. Disable these formatting parameters.
C++ ReviewEECE 3526 Example Code #include main() { cout.width(10); //sets width to 10 cout << “hello” << endl; cout.setf(ios::left); cout << “hello” << endl; cout << 16 << endl; cout.setf(ios::hex); cout << 16 << endl; } hello Output
C++ ReviewEECE 3527 Input #include Tell the linker we are doing basic I/O cin The input object. It retrieves input from the keyboard >> The extractor operator.
C++ ReviewEECE 3528 Example Code #include main () { int userInput; cout << “Enter number:”; cin >> userInput; cout << “You entered ” << userInput << endl; } Enter number:12345 You entered Output
C++ ReviewEECE 3529 I/O From a File I/O from a file is done in a similar way. #include main() { int inputNumber; ofstream myOutputFile(“outfile”); ifstream myInputFile(“infile”); myOutputFile << “text to file.” << endl; myInputFile >> inputNumber; }
C++ ReviewEECE Classes Provide a mechanism for defining classes of objects. –We can define the class of all computers to have certain characteristics. –An instance of a computer is your home PC. Classes contain member variables and member functions.
C++ ReviewEECE Classes and Objects Mammals Humans Tigers HankPeggy Tony class inherits instance-of
C++ ReviewEECE Example Class class human { // this data is private to instances of the class int height; char name[]; int weight; public: void setHeight(int heightValue); int getHeight(); }
C++ ReviewEECE Function Definitions void human::setHeight(int heightValue) { if (heightValue > 0) height = heightValue; else height = 0; } int human::getHeight() { return(height); }
C++ ReviewEECE Example Usage // first we define the variables. int height = 72; int result = 0; human hank; //set our human’s height hank.setHeight(height); //get his height result = hank.getHeight(); cout << “Hank is = “ << result << “inches tall” << endl; Hank is 72 inches tall Output