CSE 230 - C++ Notes 1 - SUNY

advertisement
CSE 230 - C++ Notes 1
C++
•Developed by Bjarne Stroustrup at Bell Labs.
•Object-oriented extension of C (originally called “C with
classes”).
•Enhanced version of C that improves on many features.
•Superset of C.
•A “Rich” Programming Language.
•Generates machine code (compilation).
Overview of C++
•C++ as a “better C”.
•Classes and Data Abstraction.
•Operator Overloading.
•Inheritance.
•Virtual Functions and Polymorphism.
•Stream Input/Output.
•Templates.
•Exception Handling.
C++ as a “Better C”
•Introduction (comments, declarations, etc.).
•C++ Standard Library.
•Header Files.
•Inline Functions.
•References and Reference Parameters.
•Default Arguments and Empty Parameter List.
•Unary Scope Resolution.
•Function Overloading.
•Function Templates.
File Extensions
•In C
program.c
•In C++
program.cpp
First C++ Example
#include <iostream>
int main()
{
std::cout << “Hello Class… \n";
return 0;
}
Single-line comments
•In C
/* this is a comment */
•In C++ // this is a comment
•or
// this
// is
// a comment
•Also the following is acceptable:
/* this is
a comment */
Stream I/O
•In C
printf(“ enter the number \n”);
scanf ( “%d “,&no);
printf(“The number is %d\n”, no);
•In C++
std::cout << “ enter the number \n”;
std::cin >> _______;
std::cout << “ The number is “ << _______ << ‘\n’;
Stream I/O Operators
•Standard output stream: std::cout
•Stream insertion operator: << (put to)•Standard input stream: std::cin
•Stream extraction operator: >> (gives)•Standard output stream
manipulator: std::endl
std::cout << ” enter the numbers \n”;
std::cin >> no1 >> no2;
std::cout<<”no1=”<< no1<<” no2=”<< no2<< std::endl;
•Multiple insertions (extractions): concatenating, chaining, or cascading
stream insertion (extractions) operators.
Empty Parameter List
•In C
type functionName( )
type functionName(__________)
It means all argument checking is disabled (i.e.
the function call can pass any arguments it wants)
•In C++
type functionName( )
type functionName(_________)
It means the function takes no arguments .
Declarations
•A variable can be declared anywhere inside a block as
long as it is before its usage in the executable instruction.
•Example 1:
std::cout << “ enter the number \n”;
int ______;
std::cin >> _______;
•Example 2:
for (______ i = 0; i <= n ; i++) { ……. }
Declarations(cont’d)
•Example 3:
{ /* block A */
int x=________;
std::cout << “1st value of x=” << x <<‘\n’;
{ /* block B */
std::cout << “2nd value of x=” << x <<‘\n’;
int x=_______;
std::cout << “3rd value of x=” << x <<‘\n’;
}
std::cout << “4th value of x=” << x <<‘\n’;
New Data Types
•New data types can be created using enum, struct, union or class.
•Example 1:
enum boolean(________, ________); /* bool is predefined
as (true, false) */
struct name {
char first[15];
char last[20];
};
•Usage:
boolean flag;
name student;
New Data Types(cont’d)
•Example 2:
union sample {
int a;
int b;
};
•Usage:
sample u;
u.a = _______;
std::cout << u.a << “ “ << _______ <<“\n”;
Constant Qualifier •Variables, parameters
and functions may be defined as read-only (similar to final
variable in Java).
•Examples:
const int x = 0;
const int max = 1000;
•Incorrect usage:
const int n;
// n must be initialized
max = 6;
// ___________________
// Example of a C++ program: Adding Two Integers
#include <iostream>
int main()
{
int integer1;
std::cout << "Enter first integer\n";
std::cin >> ____________;
int integer2, sum;
// another declaration
std::cout << "Enter second integer\n";
std::cin >> ____________;
sum = integer1 + integer2;
std::cout << "Sum is " << sum << std::endl;
return 0; // program ended successfully
} // end function main
C++ Standard Library
• Programmers can take advantage of the rich
collection of existing classes and functions.
• It is also possible to create user defined
libraries.
••
Header Files
• Each standard library has a corresponding
header file.
• Custom defined header files end with .h.
• C compatible headers:
<cstdio>, <cstdlib>, <cmath> , <ctime>,
<cstring>, <climits>, <cctype>,<cassert>
• C++ headers:
<iostream>, <iomanip>, <fstream>,<string>
<exceptions>,<typeinfo>,<iterator>
Inline Functions
• The qualifier inline before a function’s return type
“advises” the compiler to generate a copy of the function’s
code in place.
• Multiple copies of the code are inserted.
• Compiler can ignore the inline qualifier.
• Inline function is different than #define.
• Example:
#include <iostream>
using std::cout; // help to
using std::cin; //
eliminate the
using std::endl; //
prefix std::
inline double cube( const double s ) { return s * s * s; }
int main()
{
double side;
for ( int k = 1; k < 4; k++ ) {
cout << "Enter the side length of your cube: ";
cin >> side;
cout << "Volume of cube with side "
<< side << " is " << cube( side ) << endl;
} // end for
return 0;
} // end function main
Reference Parameters
• To indicate that a parameter is passed by reference, its type
must follow by an ampersand(&).
• A reference parameter is an alias for its corresponding
arguments.
• The corresponding parameter at call time must be lvalue.
• Example:
int squareByValue( int a ) {
return a = a * a; // caller's argument not modified
}
void squareByReference( int& a ) {
a = a * a;
// caller's argument modified
}
Note: The function bodies are the same.
#include <iostream>
using std::cout;
using std::endl;
int squareByValue( int a); // parameter name is not required
void squareByReference( int& a);
int main()
{
int x = 2, z = 4;
cout << "x = " << x << " before squareByValue\n"
<< "Value returned by squareByValue: "
<< squareByValue( x ) << endl
<< "x = " << x << " after squareByValue\n" << endl;
cout << "z = " << z << " before squareByReference" << endl;
squareByReference( z ); // void function call
cout << "z = " << z << " after squareByReference" << endl;
return 0;
} // end function main
// Another example of different reference parameters
#include <iostream>
using std::cout;
using std::endl;
void increment(int a, int *b, int &c)
{
a++;
(*b)++; // What happens if this is replaced with b++ ?
c++;
}
int main()
{
int x = 10, y=20, z = 30;
increment (x, &y, z);
cout << "x =" << x << " y =" << y << " z =" << z << endl;
return 0;
} // end function main
Aliases (References)
• References can also be used as aliases for other variables
within a function.
• An alias is simply another name for the original variable.
• Reference variables must be initialized in their declarations
and cannot be reassigned as aliases to other variables.
• Example:
int count = 1;
// declare integer variable count
int &cRef = ______; // create cRef as an alias for count
++cRef;
// increment count(using its alias)
• Reassign an alias:
int secondCount = 100;
cRef = ____________; // set count to 100
Aliases (References)
• The ampersand does not distribute across a comma-
separated list of variable names while declaring multiple
references.
• Correct declaration:
int &x=a, &y=b, &z=c;
• Incorrect declaration:
int___ x=a, y=b, z=c;
Default Arguments
• Function calls commonly pass a particular value of an
argument.
• Programmer can specify that such an argument is a default
argument and provide a default value for that argument.
• When a default argument is omitted, the default value of
that argument is inserted by the compiler.
• Must be the rightmost (trailing) arguments in a function’s
parameter list.
• First occurrence of the function definition (typically
in the prototype) should include the default values.
• Default values can be constants, global variables or
function calls.
#include <iostream>
using std::cout;
using std::endl;
int boxVolume( int length = 1, int width = 1, int height = 1 );
int main()
{
cout << "The default box volume is: " << boxVolume()
<< " \nVolume for L=10, W=1,H=1 is:" << boxVolume(____)
<< " \nVolume for L=10, W=5,H=1 is:" << boxVolume(____,____)
<< " \nVolume for L=10, W=5,H=2 is:" << boxVolume(____,____,____)
<< endl;
return 0;
} // end function main
int boxVolume(int length, int width, int height )
{
return length * width * height;
} // end function boxVolume
// Another example of default arguments
:
int m=_____, n=______;
int square( int a) { return a*a };
int sample( int length = m, int width = square(n), int height = 1);
int main()
{
:
cout << ”sample result is:” << ____________ << endl;
:
:
} // end function main
int sample(int length, int width, int height )
{
:
:
} // end function sample
Type Casting
• Conversion between related basic types:
double precise = 3032.56;
float lessPrecise = static_cast <_______> (precise);
• This is equivalent to :
float lessPrecise = (float) (precise);
• Conversion between very different types:
char *str = “sample string”;
int number = reinterpret_cast <_______> (*str);
• Casting away the const of a variable:
void onlyOutput (char *str);
const char *str = “ABC”;
onlyOutput (const_cast <________> (str));
Unary Scope Resolution
• It is possible to declare local and global variables with the
same name. This causes the global variable to be hidden in
the local scope.
• The unary scope resolution operator ( :: ) provides access to
the global variable when it is hidden.
• The :: operator cannot be used to access a local variable of
the same name in the outer block.
• A global variable can be accessed directly if the name of
the global variable is not the same as the name of the local
variable.
#include <iostream>
#include <iomanip>
using std::cout; using std::endl; using std::ios;
using std::setprecision;
using std::setiosflags;
using std::setw;
const double PI = 3.14159265358979;
int main() {
const float PI = static_cast< ________ >( ::PI ); // typecast to float
cout << setprecision( _______ ) // number of decimal places
<< " Local float value of PI = " << PI
<< "\nGlobal double value of PI = " << ::PI << endl;
cout << setw( _______ ) << "Local float value of PI = "
<< setiosflags( ios::fixed | ios::showpoint )
<< setprecision( 10 ) << PI << endl;
return 0;
} // end function main. Output is displayed on the next page
Output:
Local float value of PI = 3.141592741012573242
Global double value of PI = 3.141592653589790007
Local float value of PI = 3.1415927410
Function Overloading
• Create several functions of the same name that perform
similar tasks on different data types.
• Functions of the same name can be defined as long as they
have different sets of parameters (i.e. as far as their types
are concerned)
• Compiler selects the proper function by examining the
number, types, and order of the arguments in the call.
#include <iostream>
using std::cout;
using std::endl;
int square( int x ) { return x * x; }
double square( double y ) { return y * y; }
int main()
{
cout << "The square of integer ______ is " << square( ______ )
<< "\nThe square of double _____ is " << square( ______ )
<< endl;
return 0;
} // end function main
Function Templates
• Overloaded functions perform similar operations that
involve different program logic on different data types.
• If the program logic and operations are identical for each
data type, this may be done by function templates.
• The programmer defines a single function template.
• Given the argument types provided in calls to this function,
compiler generates separate template functions to handle
each type of call appropriately.
• A function template defines a whole family of solutions.
• A template begins with template followed by list of types.
• Each type is preceded by the keyword class.
• The formal type parameters are built-in or user-defined.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
template < class _____ >
____ maximum( ____ value1, ____ value2, _____ value3 )
{
____ max = value1;
if ( value2 > max )
max = value2;
if ( value3 > max )
max = value3;
return max;
} // end function template maximum.
int main()
{
int int1, int2, int3;
cout << "Input three integer values: ";
cin >> int1 >> int2 >> int3;
cout << "Max integer is: " << maximum(_______,_______,_______ );
double double1, double2, double3;
cout << "\nInput three double values: ";
cin >> double1 >> double2 >> double3;
cout << "Max double is: "<< maximum(double1,double2, double3);
char char1, char2, char3;
cout << "\nInput three characters: ";
cin >> char1 >> char2 >> char3;
cout << "Max character is: "<< maximum(char1,char2,char3)
<< endl;
return 0;
} // end function main.
// function maximum created for type int
______ maximum(int value1, int value2, int value3 )
{
_____ max = value1;
if ( value2 > max )
max = value2;
if ( value3 > max )
max = value3;
return max;
}
Download