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

Introduction to Programming

Lecture 38
Today’s Lecture
 User Define Manipulator
 Static key word
User Define
Manipulators
Example
int i = 10 ;
cout << setwidth ( 7 ) << i <<endl ;
Parameter Less
Manipulators
cout << manipulator << otherdata ;
ostream & manipulatorName ( ostream & os ) ;
Definition
ostream & manipulatorName ( ostream & os )
{
return os << userDefinedManipulator ;
}
User Defined Manipulators
// Tab A Short Example
ostream & tab ( ostream & output )
{
return output << '\t' ;
}

// bell

ostream & bell ( ostream & output )


{
return output << '\a' ;
}

// Takes the cursr to next line

ostream & endLine ( ostream & output )


{
return output << '\n' << flush ;
}

void main ( )
{

cout << "Virtual " << tab << "University" << bell << endLine ; // Use of Mainpulator

}
Static
Static
Are variables which exist for a
certain amount of time which is
longer than an ordinary automatic
variable.
Global
Example
int i ;
void myfunction ( void )
{
int i ;
for ( i = 0 ; i < 10 ; i ++ )
cout << i << endl ;
}
Automatic
Variable
State
static int i ;
static int i = 0 ; //Initialization
.........
i = 0 ; //Ordinary Assignment Statement
void f ( void )
Example
{
static int i = 0 ;
i ++ ;
cout << “Inside function f value of i : ” << i << endl ;
}
main ( )
{
int j ;
for ( j = 0 ; j < 10 ; j ++ ) ;
f();
}
Example
class Truck
{
char a ;
public :
Truck ( char c )
{
a=c;
cout << "Inside constructor for object " << a << endl ;
}

~ Truck ( )
{
cout << "Inside destructor for object " << a << endl ;
}
};
Example
Truck a ( 'A' ) ;
main ( )
{
Truck b ( 'B' ) ;
f();
g();
cout << “Function g has been called " << endl ;
}
Example
void f ( )
{
Truck c ( 'C' ) ;
}
void g ( )
{
static Truck g ( 'G' ) ;
}
Example
Output
Inside constructor for object A
Inside constructor for object B
Inside constructor for object C
Inside destructor for object C
Inside constructor for object G
function g has been called
Inside destructor for object B
Inside destructor for object G
Inside destructor for object A
Static Data
Member Inside
A Class
File
Scope
class Truck
Example
{
public :
int wheels ;
int seats ;
};
main ( )
{
Truck A ;
A.seats ;
}
::
Scope Resolution Operator
Truck :: nameOfStaticDatamember = values ;
Example
class SavingsAccount
{
private :
char name [ 30 ] ;
float accountNumber ;
float currentBalance ;
static float profitRate ;
// ...
public :
SavingsAccount ( ) ;
//...
};
SavingsAccount :: profitRate = 3.0 ;
SavingsAccount A ;
A.profitRate ; // bad usage
A.profitRate = 4.0 ; // bad usage
SavingsAccount :: profitRate ;
Example
class Student
{
public :
static int howMany ;
Student ( ) { howMany ++ ; }
~ Student( ) { howMany -- ; }
void displayHowMany ( )
{
cout << "Number of students are " << howMany ;
}
};
int Student :: howMany = 0 ;
Dynamic
What we covered today

 Parameter Less Manipulation


 Static Data

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