C++ For Beginners

提醒:本文发布于 天前,内容可能因【技术时效性】过期 或【被重新修改】,请谨慎参考。

Intro

This is my attempt to learn and document C++, While following the text: “C++ Program Design
An Introduction To Programming and Object-Oriented Design”

Prerequisite

My Current Set up :

Hello World

1
2
3
4
5
6
7
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
  • The top 3 lines will start almost all programs in C++
1
2
3
#include <iostream>
#include <string>
using namespace std;
  • This shows that program will use the iostream library to do inputs and outputs.
  • Line 1 and 2 are know as a preprocessor which are programs that run before the compiler.
  • Line 3 Indicates that the program will be using objects that are named in a special region called std
1
int main()
  • Line 4 is know as a function which specifies the return value
  • The main method is the first function that is called when the program is compiled and executed.
  • The Word “Int” indicates the return type I this case Int is Integer. in C++ the main method will always return and int.
  • The word “main” is the name of the method
  • The () are used to delimit any arguments, in this case the main method does not require arguments.
  • The { } group together statements, and in this case this these statements make up the function.
1
2
cout << "Hello, World!" << endl;
return 0;
  • The first statement starts with cout which is an object that indicates an output stream
  • The << inserts a element in this case to the output stream
  • Following this we have “Hello World” this is out output string that would display when the program is run.
  • Then the end of the first statement is end with endl this is know as a manipulator and this indicates a new line.
  • The second statement “return 0;” would be returned by the main method, a zero indicates that the program ran without issues.
  • A non zero output would mean that there was some error with the execution of the method.

User Inputs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;
int main() {
// cout << "Hello, World!" << endl;
cout << "Purchase price ?";
float Price;
cin >> Price;

//compute the output sales tax
cout << "Sales tax on $" << Price << " is ";
cout << "$" << Price * 0.04 << endl;
return 0;
}
  • The following ask the user for the input to calculate the sales tax of a purchase.
1
float Price;
  • Here im creating a variable that will store the Price as a floating point number.
  • this is because the expected input could be a number with a decimal place (ex. 5.99).
1
cin >> Price;
  • Cin is an object like cout, however Cin is an input stream
  • The users input value is converted to the internal format for floating point number and stores in the Price object.
1
2
cout << "Sales tax on $" << Price << " is ";
cout << "$" << Price * 0.04 << endl;
  • The last statements will output the price then followed by the calculated sales tax.

Comments

  • Comments is a mechanism that allows programmers to add prose or comments in code
  • Comments are ignored by the compiler, generally used to describe what a piece of code is doing.
1
2
3
4
5
6
7
// Here is a comment that span one line 
/* This a comment that can span
MULTIPLE

LINES

*/

Objects

Integer

  • In C++ the basic integer type is called an int
  • The compiler and underling hardware determine the size of int
    • for example most pc support size of 16 bits, where int can represent integers from -32768 - 32768
    • for unix it would be 32 bits and newer system can support up to 64 bit integers.
  • There are also several other integer object types like short and long
    • C++ does not determine the size of short or long however it does specfy the following:
      NumberOfBitsshort $\leq$ NumberOfBitsint $\leq$ NumberOfBitslong

Character

  • Closely related to integer object the character object (CHAR) are represented by integers

  • ASCII is a character set that is used for computers to interpret characters based on a corespondent number.

  • because characters can be represented as number the following will always be true
    ‘a’ < ‘b’ < ‘c’ < ….. < ‘z’
    ‘A’ < ‘B’ < ‘C’ < ….. < ‘Z’
    and
    ‘0’ < ‘1’ < ‘2’ < ….. < ‘9’

  • this is relationship is useful as it allows characters to be sorted, ex. alphabetically , etc..

Floating Point

  • Floating points object are used to represent real numbers, that is, numbers that have both an integer part and a fractional part.
    Ex. 3.1412

  • C++ comes with support for the 3 types of floating point numbers

    1. Float
    2. Double
    3. Long Double
  • and these types are represented as subsets of one and other so:
    Float is a subset of double and double is a subset of long double

Constants

String and character constants

  • String constants is a sequence of zero or more characters enclosed in double quotes
1
" Hello World " 
  • there are also characters know as escape characters:
1
"Hello World!\n"
  • here the \n would indicate that the character n is not a character but rather should be interpreted as a new line.
Character Name ASCII Name C++ Escape Sequence
newline NL \n
horizontal tab HT \t
vertical tab VT \v
backspace BS \b
form feed FF \f
alert or bell BEL \a
carriage return CR \r
vertical tab VT \v
backslash \ \
single quote '
double quote "
question mark ? ?

Integer constants

  • The simplest way to write an integer constant in C++ would be to write:
1
23 45 125 990
  • by default an integer would be interpreter by C++ as an int
  • you can append a l or L at the end of a number to treat a number as a long
1
23L 45L 125L 990L
  • If an integer constant does not have a suffix the compiler will choose the type depending on the size
  • It will try int first and if the number is to big then it will try to store it in a long
  • and if the value is still to long it will through an error

Floating point constants

  • layout for floating point constants
    digits.digits[f | F | l | L]

  • the constant will consist of:

    1. sequence of number before the .
    2. sequence of numbers after the .
    3. optional type specifiers
    4. also 1 or 2 could be omitted (ex. 0.5 or 1.0)
  • like integers constants float constants by default are read as double unless otherwise specified

  • the suffix option are as follows:

    1. f, F = float
    2. l, L = long double
  • in C++ floating point numbers can be represented in scientific notation:
    1.23x10[^3]

    which is read as

    1230.0

  • the general for is a followed
    mantissa x 10 [^exponent]

    and the syntax is a follows

    Digits.Digits[Exponent] [f | F | l | L]

either the whole part or fraction part can be omitted, but not both

where the exponent is 

(e | E) [+ | -] Digits 
  • The mantissa can be an integer or a decimal number. The expoents is a signed integer.
    Ex: 1.23E10 , 0.23E-4, 45.e+23, 23.68E12

Keywords

asm else operator throw
auto enum private true
bool explicit protected try
break extern public typedef
case false register typeid
catch float reinterpret_cast typename
char for return union
class friend short unsigned
const goto signed using
const_cast if sizeof virtual
continue inline static void
default int static_cast volatile
delete long struct wchar_t
do mutable switch while
double namespace template dynamic_cast
new this
  • keywords have special meaning to the compiler and they CANNOT be changed by the programmer.
  • these are also case sensitive, which consist of lowercase letters only.

Identifiers

  • names that are defined by the programmer
  • the rule for forming a valid identifier name is that it must be valid c++ name and cannot clash with any of the existing keywords.
    ex. n, price, x, numberOfPeople, getName, ….. etc
  • use clear and human readable name for the identifiers so that it helps with code readability.

Definition

  • To use an object in C++ you must first define the object

a Common form of a C++ definition is
Type Id, Id, ….., Id;

ex: int Sum;
  • Here I defined an integer object who identifier is Sum;
  • Also in this case the object is defined with no initial value, however memory is still allocated for the creation of this object.
    Other ex:
    • int x
    • int WordCnt, Radius, Height;
    • float FlightTime, Mileage, Speed;
  • all of the above are defined but not initialized.
  • generally it not recommend to define and not assign some value to an object as that could lead to an unified error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;
int main() {
float f;
char c;
int i;
double d;
cout << "f's value is " << f << endl;
cout << "i's value is " << i << endl;
cout << "c's value is " << c << endl;
cout << "d's value is " << d << endl;

return 0;
}
  • when the following is executed, the program outputs
1
2
3
4
f's value is 1.81825e+11
i's value is 8653
c's value is e
d's value is 1.12975e-231
  • As you can see the output can be unpredictable if objects are not initialized.
  • Another form of definition allows objects to be initialized when they are defined
    Type Id = Const, Id = Const ….., Id = Const;
  • In practice it is:
    int Sum = 0;
    float TaxRate = 0.06;
    char Letter = ‘a’;

Expressions

Simple Expression

  • The simplest form of the C++ expression is a constant with no operation applied
    ex.
    23;
  • Here the results yields <23, int>, and the ; after the expression is the C++ delimiter that separates or terminates an expression.
    ex.
    ‘a’;
  • Here the results yields <97, int>
  • An expression can also be an object with no operation applied. The result of evaluating this type of expression is the value of the object.
    ex.
    int XCoord = 23;
    XCoord;
  • The result of evaluating the expression is <23, int>. In some sense, an operation is being applied to the operand XCoord. The operation being applied is one that fetches the value stored in XCoord.

Binary arithmetic operations

  • Arithmetic operations for integers
Operation Operator Example Result
Addition + 2+3; <5,int>
Subtraction - 4-7; <-3,int>
Multiplication * 3*4; <12,int>
Division / 8/2; <4,int>
Remainder % 10%3; <1,int>
TOC
  1. 1. Intro
  2. 2. Prerequisite
  3. 3. Hello World
  4. 4. User Inputs
  5. 5. Comments
  6. 6. Objects
    1. 6.1. Integer
    2. 6.2. Character
    3. 6.3. Floating Point
  7. 7. Constants
    1. 7.1. String and character constants
  8. 8. Integer constants
  9. 9. Floating point constants
  10. 10. Keywords
  11. 11. Identifiers
  12. 12. Definition
    1. 12.1. Expressions
  13. 13. Simple Expression
  14. 14. Binary arithmetic operations