SlideShare uma empresa Scribd logo
1 de 15
Baixar para ler offline
An Incomplete C++ Primer

            University of Wyoming MA 5310

                  Professor Craig C. Douglas

http://www.mgnet.org/~douglas/Classes/na-sc/notes/C++Primer.pdf
C++ is a legacy programming language, as is other languages such as

                     Language        First appeared
                     Fortran         mid 1950’s
                     C               1970
                     Pascal          mid 1970’s
                     Modula 2        late 1970’s
                     Java            1990’s
                     C#              2000’s

and others. All of these languages

  • require a significant learning curve,
  • are easy to make mistakes in that are hard to find, and
  • are hard for others to decode (in large part because programmers
    fail to adequately comment codes or use badly named data
    variables).
  • exist to manipulate data using algorithms.


                                     2
3
Textbook useful hints (by page)

  •   10-36: basics
  •   87-97: arrays
  •   108-110: switch statements
  •   126-127: compound assignment
  •   128-138: classes
  •   141: cerr

MPI (by page)

  • 71-80: basics
  • 651-676: the works




                                     4
hello-simple.cpp

A simple first program is the hello, world program:

    // my first program in C++

    #include <iostream>
    using namespace std;

    int main (int argc, char** argv)   /* command line argument info */
    {
      cout << "Hello World!n";        // cout is standard character output
      return 0;
    }

argc is the number of arguments.

argv is a pointer to an array of character pointers that hold each of the arguments
given to the program when it runs.



                                                  5
Compile the file with g++, e.g.,

    g++ hello-simple.cpp –o hello-simple

Run the program with

    ./hello-simple

Some people like to add an extension .exe on executables. Tastes vary.

g++ is available on Linux and OS X systems easily. On Windows, you can
install it natively or after installing Cygwin (or Cygwin/X is better).




                                       6
Major parts of C++

  • Data types
      o Integer: int, short, short int, long, long int
      o Floating point: float, double, long double
      o Character: char
      o User defined
  • Classes
      o A container for functions (called methods) about complicated data
        structures with public, protected, and private data.
      o Classes can be combined through inheritance to be quite complicated.
  • Templates
      o A mechanism to define a class for a wide variety of data instead of
        statically defined data, e.g., define a vector class for int, float, double
        with a single source code. Which data type is actually used is
        determined when a class is used in a program declaration. Yikes.
  • Functions
      o Independent programs that implement algorithms.


                                          7
Data types

 Type          Subtype                  Size        Description
 Integer       int                      32 or 64    standard sized
               long or long int         32 or 64    bigger is better
               short or short int       16 or 32    Legacy
 Floating      float                    32          single precision
 Point         double                   64          double precision
               long double              128         quad precision
 Character     char                     8 or 16     single character

Arrays

  char name[100];              // 100 characters, indexed 0-99
  char me[] = “Craig Douglas”; // array size computed by compiler
  double matrix[10][20];       // 10 rows, 20 columns




                                    8
Functions

  Output + Function name ( Arguments )


Pointers and References

  char* who;

  who = me;
  cout << who[0] << endl;                // endl = end of line (‘n’)
  who[0] = ‘c’;
  who[6] = ‘d’;
  cout << who << endl;                   // me is now in lower case

  who = name;
  cout << who[0] << who[1] << endl;      // 1st 2 characters



                                  9
References are used in function declarations and are similar to pointers:

    double inner_product( double& x, double& y, int len ) {

         double ip; // return value

         for( int i = 0, ip = 0.0; i < len; i++ )        // 0 <= i < len
               ip += ( x[i] * y[i] );                    // for loop’s one statement

         return ip;                                      // or just ip;
         }

Here are lots of new things: a for loop with a local variable definition, an
increment operator, and a complicated assignment statement inside the loop.

References (double& x) differ from pointers (double* x) only that the data in a
reference variable will not change. In the inner_product function, neither x nor y
will change, so they can be reference variables. Compilers can do better
optimizations on read only variables that on ones that can be changed.



                                                    10
Classes

Two distinct parts should be defined:

  1. A header file with declarations and method (function) headers.
  2. An implementation file that is compiled.

The header file should have the following sections:

  • private: all hidden variables and members are declared here.
  • protected: only classes declared as a friend are declared here.
  • public: members that can be accessed by anyone.
      o Constructors, the destructor, and copy members should be defined.
      o Access members and algorithmic members should be defined.




                                        11
A sample header file for a class hello is hello.h:

    #ifndef H_class_hello
    #define H_class_hello

    class hello {

      private:

         char greeting[100];

      public:

         hello();                          // constructor, no arguments
         hello(const char*);               // constructor, 1 argument (greeting)
         virtual ~hello();                 // destructor
         hello(hello& the_other_hello);    // copy constructor
         void set_greeting(const char*);   // set greeting
         void print_greeting();            // print greeting
    };
    #endif




                                               12
The implementation file, hello.cpp, could be as simple as

    #include "hello.h"

    #include <iostream>
    #include <string>
    using namespace std;

    hello::hello() { char ini = 0; set_greeting(&ini); }

    hello::hello(const char* msg) { set_greeting(msg); }

    hello::~hello() { }

    hello::hello(hello& the_other_hello) {
      hello(the_other_hello.greeting); }

    void hello::set_greeting(const char* msg) { strcpy(greeting, msg); }

    void hello::print_greeting() { cout << greeting << endl; }

You should study one of the classes in the textbook’s cdrom disk.


                                                  13
Compound Statements

C++ has many compound statements, including
 • if ( clause ) statement else if (clause ) statement … else (clause ) statement
      o else if and else are optional
      o many times statement is actually { statements }
 • for( initialize ; stopping condition ; updates at end of loop ) statement
      o initilize can be multiple items separated by commas
      o stopping condition is anything appropriate inside an if clause
      o updates are comma separated items
      o usually there is only one item, not multiple
 • while ( true condition ) statement
      o true condition is anything appropriate inside an if clause
 • switch ( variable ) { case value: statements break … default: statements }
      o multiple case statements can occur without a statement between them
      o default is optional
      o remember the break or the computer will continue into the next case
         (unless this is desired)


                                        14
One of C++’s strengths and weakness is the ability to overload operators. A very
good online source of information about how overload any operator in C++ is
given at the URL

    http://www.java2s.com/Tutorial/Cpp/0200__Operator-
    Overloading/Catalog0200__Operator-Overloading.htm

C++ has a Template mechanism that allows classes to be automatically defined
for different data types. There is even a Standard Template Library (STL) that
covers many useful template types.

Useful tutorials can be found at

  • http://www.cplusplus.com/doc/tutorial/
  • http://www.cplusplus.com/files/tutorial.pdf
  • http://www.java2s.com/Tutorial/Cpp/CatalogCpp.htm




                                       15

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
OpenGurukul : Language : Python
OpenGurukul : Language : PythonOpenGurukul : Language : Python
OpenGurukul : Language : Python
 
C Basics
C BasicsC Basics
C Basics
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Chapter 2 basic element of programming
Chapter 2 basic element of programming Chapter 2 basic element of programming
Chapter 2 basic element of programming
 
OpenGurukul : Language : PHP
OpenGurukul : Language : PHPOpenGurukul : Language : PHP
OpenGurukul : Language : PHP
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
java vs C#
java vs C#java vs C#
java vs C#
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
C++ language
C++ languageC++ language
C++ language
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
Create your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 VeronaCreate your own PHP extension, step by step - phpDay 2012 Verona
Create your own PHP extension, step by step - phpDay 2012 Verona
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
20 ruby input output
20 ruby input output20 ruby input output
20 ruby input output
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Java 8
Java 8Java 8
Java 8
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 

Semelhante a C++primer

Semelhante a C++primer (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C tutorial
C tutorialC tutorial
C tutorial
 
PRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptxPRINCE PRESENTATION(1).pptx
PRINCE PRESENTATION(1).pptx
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorials
C tutorialsC tutorials
C tutorials
 
C programming language
C programming languageC programming language
C programming language
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
C++
C++C++
C++
 
C tutorial
C tutorialC tutorial
C tutorial
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C language updated
C language updatedC language updated
C language updated
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 

Último

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 

Último (20)

Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 

C++primer

  • 1. An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/Classes/na-sc/notes/C++Primer.pdf
  • 2. C++ is a legacy programming language, as is other languages such as Language First appeared Fortran mid 1950’s C 1970 Pascal mid 1970’s Modula 2 late 1970’s Java 1990’s C# 2000’s and others. All of these languages • require a significant learning curve, • are easy to make mistakes in that are hard to find, and • are hard for others to decode (in large part because programmers fail to adequately comment codes or use badly named data variables). • exist to manipulate data using algorithms. 2
  • 3. 3
  • 4. Textbook useful hints (by page) • 10-36: basics • 87-97: arrays • 108-110: switch statements • 126-127: compound assignment • 128-138: classes • 141: cerr MPI (by page) • 71-80: basics • 651-676: the works 4
  • 5. hello-simple.cpp A simple first program is the hello, world program: // my first program in C++ #include <iostream> using namespace std; int main (int argc, char** argv) /* command line argument info */ { cout << "Hello World!n"; // cout is standard character output return 0; } argc is the number of arguments. argv is a pointer to an array of character pointers that hold each of the arguments given to the program when it runs. 5
  • 6. Compile the file with g++, e.g., g++ hello-simple.cpp –o hello-simple Run the program with ./hello-simple Some people like to add an extension .exe on executables. Tastes vary. g++ is available on Linux and OS X systems easily. On Windows, you can install it natively or after installing Cygwin (or Cygwin/X is better). 6
  • 7. Major parts of C++ • Data types o Integer: int, short, short int, long, long int o Floating point: float, double, long double o Character: char o User defined • Classes o A container for functions (called methods) about complicated data structures with public, protected, and private data. o Classes can be combined through inheritance to be quite complicated. • Templates o A mechanism to define a class for a wide variety of data instead of statically defined data, e.g., define a vector class for int, float, double with a single source code. Which data type is actually used is determined when a class is used in a program declaration. Yikes. • Functions o Independent programs that implement algorithms. 7
  • 8. Data types Type Subtype Size Description Integer int 32 or 64 standard sized long or long int 32 or 64 bigger is better short or short int 16 or 32 Legacy Floating float 32 single precision Point double 64 double precision long double 128 quad precision Character char 8 or 16 single character Arrays char name[100]; // 100 characters, indexed 0-99 char me[] = “Craig Douglas”; // array size computed by compiler double matrix[10][20]; // 10 rows, 20 columns 8
  • 9. Functions Output + Function name ( Arguments ) Pointers and References char* who; who = me; cout << who[0] << endl; // endl = end of line (‘n’) who[0] = ‘c’; who[6] = ‘d’; cout << who << endl; // me is now in lower case who = name; cout << who[0] << who[1] << endl; // 1st 2 characters 9
  • 10. References are used in function declarations and are similar to pointers: double inner_product( double& x, double& y, int len ) { double ip; // return value for( int i = 0, ip = 0.0; i < len; i++ ) // 0 <= i < len ip += ( x[i] * y[i] ); // for loop’s one statement return ip; // or just ip; } Here are lots of new things: a for loop with a local variable definition, an increment operator, and a complicated assignment statement inside the loop. References (double& x) differ from pointers (double* x) only that the data in a reference variable will not change. In the inner_product function, neither x nor y will change, so they can be reference variables. Compilers can do better optimizations on read only variables that on ones that can be changed. 10
  • 11. Classes Two distinct parts should be defined: 1. A header file with declarations and method (function) headers. 2. An implementation file that is compiled. The header file should have the following sections: • private: all hidden variables and members are declared here. • protected: only classes declared as a friend are declared here. • public: members that can be accessed by anyone. o Constructors, the destructor, and copy members should be defined. o Access members and algorithmic members should be defined. 11
  • 12. A sample header file for a class hello is hello.h: #ifndef H_class_hello #define H_class_hello class hello { private: char greeting[100]; public: hello(); // constructor, no arguments hello(const char*); // constructor, 1 argument (greeting) virtual ~hello(); // destructor hello(hello& the_other_hello); // copy constructor void set_greeting(const char*); // set greeting void print_greeting(); // print greeting }; #endif 12
  • 13. The implementation file, hello.cpp, could be as simple as #include "hello.h" #include <iostream> #include <string> using namespace std; hello::hello() { char ini = 0; set_greeting(&ini); } hello::hello(const char* msg) { set_greeting(msg); } hello::~hello() { } hello::hello(hello& the_other_hello) { hello(the_other_hello.greeting); } void hello::set_greeting(const char* msg) { strcpy(greeting, msg); } void hello::print_greeting() { cout << greeting << endl; } You should study one of the classes in the textbook’s cdrom disk. 13
  • 14. Compound Statements C++ has many compound statements, including • if ( clause ) statement else if (clause ) statement … else (clause ) statement o else if and else are optional o many times statement is actually { statements } • for( initialize ; stopping condition ; updates at end of loop ) statement o initilize can be multiple items separated by commas o stopping condition is anything appropriate inside an if clause o updates are comma separated items o usually there is only one item, not multiple • while ( true condition ) statement o true condition is anything appropriate inside an if clause • switch ( variable ) { case value: statements break … default: statements } o multiple case statements can occur without a statement between them o default is optional o remember the break or the computer will continue into the next case (unless this is desired) 14
  • 15. One of C++’s strengths and weakness is the ability to overload operators. A very good online source of information about how overload any operator in C++ is given at the URL http://www.java2s.com/Tutorial/Cpp/0200__Operator- Overloading/Catalog0200__Operator-Overloading.htm C++ has a Template mechanism that allows classes to be automatically defined for different data types. There is even a Standard Template Library (STL) that covers many useful template types. Useful tutorials can be found at • http://www.cplusplus.com/doc/tutorial/ • http://www.cplusplus.com/files/tutorial.pdf • http://www.java2s.com/Tutorial/Cpp/CatalogCpp.htm 15