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

c 

 
A) Basic Components and structure of C++ program
ÀÀ   
   

    

  std;
Hello World!
  main ()
{
cout << "Hello World!";
 0;
}

The first panel (in light blue) shows the source code for our first program. The second one (in
light gray) shows the result of the program once compiled and executed. To the left, the grey
numbers represent the line numbers - these are not part of the program, and are shown here
merely for informational purposes.

The way to edit and compile a program depends on the compiler you are using. Depending on
whether it has a Development Interface or not and on its version. Consult the compilers section
and the manual or help included with your compiler if you have doubts on how to compile a C++
console program.

The previous program is the typical program that programmer apprentices write for the first time,
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C++, but it already contains the fundamental components that
every C++ program has. We are going to look line by line at the code we have just written:

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behavior of the program. The programmer
can use them to include short explanations or observations within the source code itself.
In this case, the line is a brief description of what our program is.
#include <iostream>

Lines beginning with a hash sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In
this case the directive #include <iostream> tells the preprocessor to include the iostream
standard file. This specific file (iostream) includes the declarations of the basic standard
input-output library in C++, and it is included because its functionality is going to be used
later in the program.
using namespace std;

All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name . So in order to access its functionality we
declare with this expression that we will be using these entities. This line is very frequent
in C++ programs that use the standard library, and in fact it will be included in most of
the source codes included in these tutorials.
int main ()

This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution, independently of its
location within the source code. It does not matter whether there are other functions with
other names defined before or after it - the instructions contained within this function's
definition will always be the first ones to be executed in any C++ program. For that same
reason, it is essential that all C++ programs have a   function.

The word main is followed in the code by a pair of parentheses (()). That is because it is
a function declaration: In C++, what differentiates a function declaration from other types
of expressions are these parentheses that follow its name. Optionally, these
parentheses may enclose a list of parameters within them.

Right after these parentheses we can find the body of the main function enclosed in
braces ({}). What is contained within these braces is what the function does when it is
executed.
cout << "Hello World!";

This line is a C++ statement. A statement is a simple or compound expression that can
actually produce some effect. In fact, this statement performs the only action that
generates a visible effect in our first program.

cout is the name of the standard output stream in C++, and the meaning of the entire
statement is to insert a sequence of characters (in this case the Hello World sequence of
characters) into the standard output stream ( , which usually corresponds to the
screen).

  is declared in the    standard file within the  namespace, so that's why we
needed to include that specific file and to declare that we were going to use this specific
namespace earlier in our code.

Notice that the statement ends with a semicolon character (;). This character is used to
mark the end of the statement and in fact it must be included at the end of all expression
statements in all C++ programs (one of the most common syntax errors is indeed to
forget to include some semicolon after a statement).
return 0;

The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code with a value of zero). A return
code of  for the   function is generally interpreted as the program worked as
expected without any errors during its execution. This is the most usual way to end a
C++ console program.

You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines
with directives for the compiler's preprocessor (those beginning by #). Then there were lines that
began the declaration of a function (in this case, the main function) and, finally lines with
statements (like the insertion into  ), which were all included within the block delimited by the
braces ({}) of the main function.

B) Steps in compiling and executing a C++ program

Depending on your computer and your compiler, the process of compiling your program varies.
For now, we'll assume that you are using a UNIX machine and the gcc compiler. Gcc is a free
compiler which is available on virtually all UNIX systems.

To compile your program, type the following command at a UNIX prompt:

g++ hello.C -o hello


Make sure that g++ is in your path and that you are running it in the directory containing hello.C.

Congratulations - you've just compiled your first C++ program! The program is called hello and
is located in the same directory containing the file hello.C. To run your program, simply type
hello at your UNIX prompt. You should see the following output:

# hello
Hello, World!
#
That's all there is to i

ü 
 
A) if statements

The first type of branching statement we will look at is the     . An     has the
form:

 (  )
{
// code to execute if   is true
}
 
{
// code to execute if   is false
}
In an     ,   is a value or an expression that is used to determine which code
block is executed, and the curly braces act as "begin" and "end" markers.

Here is a full C++ program as an example:

//include this file for cout


#include <iostream.h>

int main() {
// define two integers
int x = 3;
int y = 4;
//print out a message telling which is bigger
if (x > y) {
cout << "x is bigger than y" << endl;
}
else {
cout << "x is smaller than y" << endl;
}
return 0;
}

` 
 
   

The next branching statement is called a  


   . A  
   is used in
place of many     .

The  
   allows a programmer to compound a group of     , provided
that the condition being tested is an integer. The switch statement has the form:

 
( 
 ){
  :
// code to execute if  
  is  
;
...
   :
// code to execute if  
  is  
;
  :
// code to execute if  
  is none of the above
}

The   clause is optional, but it is good programming practice to use it. The default clause
is executed if none of the other clauses have been executed. For example, if my code looked
like:

switch (place) {
case 1:
cout << "we're first" << endl;
break;
case 2:
cout << "we're second" << endl;
break;
default:
cout << "we're not first or second" << endl;
}

This switch statement will write "we're first" if the variable   is equal to 1, it will write "we're
second" if   is equal to 2, and will write "we're not first or second" if   is any other
value.
 
       () is a ternary operator (it takes three operands). The
conditional operator works as follows:

× The first operand is implicitly converted to  . It is evaluated and all side effects are
completed before continuing.
× If the first operand evaluates to  (1), the second operand is evaluated.
× If the first operand evaluates to   (0), the third operand is evaluated.

The result of the conditional operator is the result of whichever operand is evaluated ² the
second or the third. Only one of the last two operands is evaluated in a conditional expression.

Conditional expressions have right-to-left associativity. The first operand must be of integral or
pointer type. The following rules apply to the second and third expressions:

× If both expressions are of the same type, the result is of that type.
× If both expressions are of arithmetic or enumeration types, the usual arithmetic
conversions (covered in Arithmetic Conversions) are performed to convert them to a
common type.
× If both expressions are of pointer types or if one is a pointer type and the other is a
constant expression that evaluates to 0, pointer conversions are performed to convert
them to a common type.
× If both expressions are of reference types, reference conversions are performed to
convert them to a common type.
× If both expressions are of type void, the common type is type void.
× If both expressions are of a given class type, the common type is that class type.

Any combinations of second and third operands not in the preceding list are illegal. The type of
the result is the common type, and it is an l-value if both the second and third operands are of
the same type and both are l-values.

// expre_Expressions_with_the_Conditional_Operator.cpp
// compile with: /EHsc
// Demonstrate conditional operator
#include <iostream>
using namespace std;
int main() {
int i = 1, j = 2;
cout << ( i > j ? i : j ) << " is greater." << endl;
}

*          


 
  

  

    
     

  
   

int main()
{
double a[100][100];
double b[100][100];
double mValue;
double nValue;
double pValue;
char ans;
char response;

do{
cout<<"\t\tM A T R I X M U L T I P L I C A T I O N\n\n\n";
cout<<"This program will compute the product of two matrices.\n";
cout<<"\nAmxn and Bnxp, \n\nwhere m and p less than or equal to n (m, p <= n )\n";
cout<<"To use the program, just follow what the program asks.";
cout<<"Want to use the program? : \n";
cout<<"type 'y' to continue and press any key to EXIT then press ENTER: ";
cin>>response;

if((response=='y')||(response=='Y'))
{
cout<<"\n\nEnter the value of m: ";
cin>>mValue;
while(mValue<=0)
{
cout<<"\n\nINCORRECT dimension(s), no negative or zero dimension(s) in a matrix\n";
cout<<"\nEnter the value of m greater than "<<mValue<<" : ";
cin>>mValue;
}
cout<<"\nEnter the value of p: ";
cin>>pValue;
while(pValue<=0)
{
cout<<"\n\nINCORRECT dimension(s), no negative or zero dimension(s) in a matrix\n";
cout<<"\nEnter the value of p greater than "<<pValue<<" : ";
cin>>pValue;
}
cout<<"\nEnter the value of n: ";
cin>>nValue;
while(nValue<0)
{ nValue = 0;
cout<<"\nEnter the value of n greater than "<<nValue<<" and less than
"<<pValue<<" or "<<mValue<<" : ";
cin>>nValue;
}
while((nValue>mValue)||(nValue>pValue))
{
if(mValue>pValue)
{
cout<<"\nERROR:\n\tValue of n must be less than or equal to
"<<pValue<<"\n\n";
cout<<"Enter the value of n: ";
cin>>nValue;
}
else
{
cout<<"\nERROR:\n\tValue of n must be less than or equal to "<<mValue<<"\n\n";
cout<<"Enter the value of n: ";
cin>>nValue;
}
}

cout<<"\n\nEnter a <strong class="highlight">matrix</strong> with


this dimension(s) A "<<mValue<<"x"<<nValue<<": \n";
cout<<"\n\nType "<<(nValue*mValue)<<" entries for <strong
class="highlight">matrix</strong> A: \n\n";

for(int i=0; i<mValue; i++)


{
for(int j=0; j<nValue; j++)
cin>>a[i][j];
}

cout<<"\nThe value of <strong class="highlight">matrix</strong> A


that you have entered: \n\n";
for(int i=0; i<mValue; i++)
{
for(int j=0; j<nValue; j++)
cout<<a[i][j]<<"\t";
cout<<endl;
}
cout<<"\n\nEnter a <strong class="highlight">matrix</strong> with
this dimension(s) B "<<nValue<<"x"<<pValue<<": \n";
cout<<"\n\nType "<<(nValue*pValue)<<" entries for <strong
class="highlight">matrix</strong> B: \n\n";

for(int i=0; i<nValue; i++)


{
for(int j=0; j<pValue; j++)
cin>>b[i][j];
}
cout<<"\nThe value of <strong class="highlight">matrix</strong> B that
you have entered: \n\n";
for(int i=0; i<nValue; i++)
{
for(int j=0; j<pValue; j++)
cout<<b[i][j]<<"\t";
cout<<endl;
}
cout<<"\n\n\nThe PRODUCT is: \n\n";
getResult(a,b,mValue,pValue,nValue);
}
else
break;
cout<<"\n\nTry again? \n\nType y to try again and press any key to stop then press ENTER. :
";
cin>>ans;
}while((ans=='y')||(ans=='Y'));

cin.get();
cin.get();
return 0;
}
}

//

A    
   '  '  
   
        


`  

void aMethod(aParameter p) { }

When passing by value a  !"# is made in memory taking up space and making
any changes to the variable  outside of the $
 scope. Once control returns to the
calling procedure any changes to the variable will not be recognized, and you will still have the
original variable.

`% 

void aMethod(aParameter& p) { }

NOTE: the & can be place either against the parameter type, against the parameter name, or
there can be a space on either side.

This essentially passes a pointer, but not the same kind of pointer you would get when creating
a:
Variable* v;
That is why it is called by reference, since that is what you have, p now acts as if it were the
parameter just like in the by value way, but any changes affect the original and stay changed
outside of the $
 scope.

*Now if that parameter was a structure, class, or template, etc. It will have fields that are
accesable by reference or pointers '(

In both cases of the above passing, the parameter passed can be accessed using the or dot
operator.
) 
*assuming fields within the class type.
Person person; //person is an object of class Person
person.name
person.Chlid.name
*It can also be used to call methods within the type.
person.getFriends() //which would likely return a vector or array

If the methods above were constructors or other member functions, accessed in a fasion like the
method call just above, then there is a
 operator for accessing the object which called it.
Who¶s fields can also be accessed, but only by pointers.

Since the object is passed implicitly it is passed as a pointer reference by default.


) 
-this now represents a pointer to a Person object
this->name
person->Child.name //if child can access it¶s name by reference it stays that way

Once again this can be done with methods.


this->getFriends()

Other examples requiring pointers:


int* i = new int(0); //this defines a dynamic int in memory pointed to by i
cout<<*i; would print the value that i points to

The * operator in both cases are *! the same!!


-the first is a pointer reference, belonging to the type, in this case int.
-the second is a de-referencing operator belonging to the variable which resolves it into the
variable it is point to.

Keep in mind that pointers are limitless:


int**** i = new int(1);
cout<<****i;

All that is needed is to dereference as many times as is originally referenced... but you're
probably thinking, "why would anyone EVER do that?"
Quick answer: arrays!!

Arrays are complicated and cumbersome to code, if there is a faster and easier way shouldn't
we do it? The answer is YES!!
By defining arrays by pointer, they are dynamic, and can be created at run time, not based on
static values, they can also be traversed in the same way thanks to the C++ ingenuity of:
sizeOf  overloading the [] operator.
I will not discuss why or how this works, maybe when i write the [] overloading function, just
know that it does.

) 
int* i = new int[3]; //defines a pointer to an array of 3 ints
cout<

It may seem strange, but it is a little complex for this recipe, and involves the stack, bytes, and
other pointers.
This again is limitless:
int** i = new int*[3]; //define a pointer to an array of pointers to ints
cout<<*i[0]; //now we must dereference the final referencing that is not array specifi

ß 
   $  +
 
      

You can derive a class from any number of base classes. Deriving a class from more than one
direct base class is called multiple inheritance.

In the following example, classes A, B, and C are direct base classes for the derived class X:

class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };

The following inheritance graph describes the inheritance relationships of the above example.
An arrow points to the direct base class of the class at the tail of the arrow:

The order of derivation is relevant only to determine the order of default initialization by
constructors and cleanup by destructors.

A direct base class cannot appear in the base list of a derived class more than once:

class B1 { /* ... */ }; // direct base class


class D : public B1, private B1 { /* ... */ }; // error

However, a derived class can inherit an indirect base class more than once, as shown in the
following example:

class L { /* ... */ }; // indirect base class


class B2 : public L { /* ... */ };
class B3 : public L { /* ... */ };
class D : public B2, public B3 { /* ... */ }; // valid

In the above example, class D inherits the indirect base class L once through class B2 and once
through class B3. However, this may lead to ambiguities because two subobjects of class L
exist, and both are accessible through class D. You can avoid this ambiguity by referring to
class L using a qualified class name. For example:

B2::L

or

B3::L.

ö 
      ,  
      

Virtual member functions are declared with the keyword virtual. They allow dynamic binding of
member functions. Because all virtual functions must be member functions, virtual member
functions are simply called virtual functions.

If the definition of a virtual function is replaced by a pure specifier in the declaration of the
function, the function is said to be declared pure. A class that has at least one pure virtual
function is called an abstract class.

class B {
public:
virtual void f();
};

class D : public B {
private:
void f();
};

int main() {
D dobj;
B* bptr = &dobj;
D* dptr = &dobj;

// valid, virtual B::f() is public,


// D::f() is called
bptr->f();

// error, D::f() is private


dptr->f();
}

/// ########
+   
      
 
 
There are 3 File I/O classes in C++ which are used for File Read/Write operations. They are

× ifstream - Can be used for File read/input operations


× ofstream - Can be used for File write/output operations
× fstream - Can be used for both read/write c++ file I/O operations

The most important methods which will be used for any file operations are:

1. fstream::open method - to open the file


2. fstream::Operator >> and fstream::Operator << - For reading from or writing to the file.
3. fstream::close - Flushes all buffer and close the file

Reading a text file using fstream class:


There are several ways of reading the text from a file. But all of them have a common
approach as follows.

1. Open the file


2. Read the data
3. Close the file

This sample code snippet explains how to use the c++ file i/o stream operators to read data
from a file. In all cases the header file   must be included.

#include<fstream.h>

int main()

char str[2000];

fstream file_op("c:\\test_file.txt",ios::in);

while(file_op >> str)

cout << str ;

file_op.close();

return 0;

}
The class fstream, which is used above is the one which is commonly used for c++ file i/o
manipulations. The constructor of fstream takes 2 parameters. One is the file path and the
second is the File Open mode. There are several open modes, each of them with a different
purpose. Some of them are ios::in for reading, ios::out for writing, ios::app for appending to the
end of file, ios::binary for opening in binary mode etc.,

Now for the purpose of this article, as the data is read from the file, the flag ios::in is used.
After this, the read operation is continued till the end of the file. The while loop ensures a
continuous read till the end of the file or it encounters any abnormal break. If the program is built
and run , it displays all the data read from the file. The C++ File I/O read job is done.

But if we look at the output closely, there is a draw back in using this stream operator read.
The output misses the white spaces and the end of line characters. In order not to miss these
characters we can either use fstream::get() or fstream::getline() methods. Here is the example
for using fstream getline method.

#include <fstream.h>

int main()

char str[2000];

fstream file_op("c:\\test_file.txt",ios::in);

while(!file_op.eof())

file_op.getline(str,2000);

cout <<str;

} file_op.close();

cout <<endl;

return 0;

}
Writing to a text file using fstream class:

Writing to a text file can also be achieved with the stream operators. This also follows the
same order of operations, though with a slight difference.

1. open a file - in write mode

2. Write to a file

3. close the file

Look at the following sample code to see the difference.

#include <fstream.h>

int main()

fstream file_op("c:\\CoderSource_file.txt",ios::out);

file_op<<"Test Write to file";

file_op.close();

return 0;

To modify the data or to seek to a different position inside the file, the c++ file i/o class fstream
provides member functions like seekg() etc., These functions can be used to relocate the record
insert position to the desired locations.

After all the C++ File I/O operations we do a fstream::close(), to close the file pointer. This is
not mandatory. Even if this function is not called by the application, the destructor of the fstream
class will close the file when the object goes out of scope

$ ) 
       
    
  

C++ Class Templates are used where we have multiple copies of code for different data types
with the same logic. If a set of functions or classes have the same functionality for different data
types, they becomes good candidates for being written as Templates.
One good area where this C++ Class Templates are suited can be container classes. Very
famous examples for these container classes will be the STL classes like vector, list etc., Once
code is written as a C++ class template, it can support all data types. Though very useful, It is
advisable to write a class as a template after getting a good hands-on experience on the logic
(by writing the code with normal data types). There are cases where we need specialization for
writing optimized code for specific data types.

//C++_Class_Templates.cpp

#include <iostream.h>
#include <vector>

template <typename T>


class MyQueue
{
std::vector<T> data;
public:
void Add(T const &);
void Remove();
void Print();
};

template <typename T> void MyQueue<T> ::Add(T const &d)


{
data.push_back(d);
}

template <typename T> void MyQueue<T>::Remove()


{
data.erase(data.begin( ) + 0,data.begin( ) + 1);
}

template <typename T> void MyQueue<T>::Print()


{
std::vector <int>::iterator It1;
It1 = data.begin();
for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ )
cout << " " << *It1<<endl;

}
//Usage for C++ class templates
void main()
{
MyQueue<int> q;
q.Add(1);
q.Add(2);

cout<<"Before removing data"<<endl;


q.Print();

q.Remove();
cout<<"After removing data"<<endl;
q.Print();
}

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