C++ Quick Syntax Reference (Mikael Olsson (auth.)) (Z-Library)

Author: Mikael Olsson (auth.)

科学

The C++ Quick Syntax Reference is a condensed code and syntax reference to the C++ programming language. It presents the essential C++ syntax in a well-organized format that can be used as a handy reference. You won’t find any technical jargon, bloated samples, drawn out history lessons, or witty stories in this book. What you will find is a language reference that is concise, to the point and highly accessible. The book is packed with useful information and is a must-have for any C++ programmer. In the C++ Quick Syntax Reference, you will find: A concise reference to the C++ language syntax. Short, simple, and focused code examples. A well laid out table of contents and a comprehensive index allowing easy review.

📄 File Format: PDF
💾 File Size: 2.0 MB
11
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
📄 Page 3
iii Contents at a Glance About the Author ���������������������������������������������������������������������������� xiii About the Technical Reviewer ��������������������������������������������������������� xv Introduction ����������������������������������������������������������������������������������� xvii Chapter 1: Hello World ■ �������������������������������������������������������������������� 1 Chapter 2: Compile and Run ■ ����������������������������������������������������������� 3 Chapter 3: Variables ■ ����������������������������������������������������������������������� 5 Chapter 4: Operators ■ �������������������������������������������������������������������� 11 Chapter 5: Pointers ■ ����������������������������������������������������������������������� 15 Chapter 6: References ■ ������������������������������������������������������������������ 19 Chapter 7: Arrays ■ ������������������������������������������������������������������������� 21 Chapter 8: String ■ �������������������������������������������������������������������������� 23 Chapter 9: Conditionals ■ ���������������������������������������������������������������� 27 Chapter 10: Loops ■ ������������������������������������������������������������������������� 29 Chapter 11: Functions ■ ������������������������������������������������������������������ 31 Chapter 12: Class ■ ������������������������������������������������������������������������� 37 Chapter 13: Constructor ■ ��������������������������������������������������������������� 41 Chapter 14: Inheritance ■ ���������������������������������������������������������������� 45 Chapter 15: Overriding ■ ����������������������������������������������������������������� 47 Chapter 16: Access Levels ■ ������������������������������������������������������������ 51
📄 Page 4
iv ■ Contents at a GlanCe Chapter 17: Static ■ ������������������������������������������������������������������������� 55 Chapter 18: Enum ■ ������������������������������������������������������������������������� 57 Chapter 19: Struct and Union ■ ������������������������������������������������������� 59 Chapter 20: Operator Overloading ■ ������������������������������������������������ 63 Chapter 21: Custom Conversions ■ ������������������������������������������������� 67 Chapter 22: Namespaces ■ �������������������������������������������������������������� 69 Chapter 23: Constants ■ ������������������������������������������������������������������ 73 Chapter 24: Preprocessor ■ ������������������������������������������������������������� 77 Chapter 25: Exception Handling ■ ��������������������������������������������������� 83 Chapter 26: Type Conversions ■ ������������������������������������������������������ 87 Chapter 27: Templates ■ ������������������������������������������������������������������ 93 Chapter 28: Headers ■ ��������������������������������������������������������������������� 99 Index ���������������������������������������������������������������������������������������������� 103
📄 Page 5
xvii Introduction C++ is a general purpose multi-paradigm programming language. It is an extension of the C language and as such most C code can easily be made to compile in C++. Some of the major additions to C include object-orientated programming, operator overloading, multiple inheritance and exception handling. The development of C++ began in 1979, seven years after C first made its appearance. Despite being what many consider legacy languages, C and C++ are still the most widely used languages in the software industry. They are used in creating everything from operating systems and embedded software to desktop applications, games and so on. Compared with newer languages, C++ applications are often more complex and take longer to develop. In return, C++ gives the programmer a tremendous amount of control in that the language provides both high-level and low-level abstractions from the hardware. It is also designed to give the programmer a lot of freedom by supporting many different programming styles or paradigms, such as procedural, object-oriented or generic programming. The compiler used in this book is the Microsoft C++ compiler. Some other common ones include Borland, Intel and GNU C++ compilers. Despite C++ being standardized in 1998, these compilers still support slightly different features. Therefore, when something applies specifically to the Microsoft compiler this will be pointed out.
📄 Page 6
1 Chapter 1 Hello World Choosing an IDE To begin developing in C++ you should download and install an Integrated Development Environment (IDE) that supports C++. A good choice is Microsoft’s own Visual Studio.1 If you do not have Visual Studio but would like to try out the examples in this book in a similar environment you can download Visual Studio Express2 from Microsoft’s website. This is a lightweight version of Visual Studio that is available for free. Alternatively, you can develop using a simple text editor – such as Notepad – although this is less convenient than using an IDE. If you choose to do so, just create an empty document with a .cpp file extension and open it in the editor of your choice. Creating a project After installing Visual Studio or Visual Studio Express, go ahead and launch the program. You then need to create a project, which will manage the C++ source files and other resources. Go to File ➤ New ➤ Project in Visual Studio, or File ➤ New Project in Visual Studio Express, to display the New Project window. From there select the Visual C++ template type in the left frame. Then select the Win32 Console Application template in the right frame. At the bottom of the window you can configure the name and location of the project. When you are finished, click the OK button and another dialog box will appear titled Win32 Application Wizard. Click next and a couple of application settings will be displayed. Leave the application type as Console application and check the Empty project checkbox. Then click Finish to let the wizard create your empty project. Adding a source file You have now created a C++ project. In the Solution Explorer pane (View ➤ Solution Explorer) you can see that the project consists of three empty folders: Header Files, Resource Files and Source Files. Right click on the Source Files folder and select Add ➤ New Item. From the Add New Item dialog box choose the C++ File (.cpp) template. Give this source file the name “MyApp” and click the Add button. An empty cpp file will now be added to your project and also opened for you. 1http://www.microsoft.com/visualstudio 2http://www.microsoft.com/express
📄 Page 7
CHAPTER 1 ■ HEllo WoRld 2 Hello world The first thing to add to the source file is the main function. This is the entry point of the program, and the code inside of the curly brackets is what will be executed when the program runs. The brackets, along with their content, is referred to as a code block, or just a block. int main() {} The first application will simply output the text “Hello World” to the screen. Before this can be done the iostream header needs to be included. This header provides input and output functionality for the program, and is one of the standard libraries that come with all C++ compilers. What the #include directive does is effectively to replace the line with everything in the specified header before the file is compiled into an executable. #include <iostream> int main() {} With iostream included you gain access to several new functions. These are all located in the standard namespace called std, which you can examine by using a double colon, also called the scope resolution operator (::). After typing this in Visual Studio, the IntelliSense window will automatically open, displaying what the namespace contains. Among the members you find the cout stream, which is the standard output stream in C++ that will be used to print text to a console window. It uses two less-than signs known as the insertion operator (<<) to indicate what to output. The string can then be specified, delimited by double quotes, and followed by a semicolon. The semicolon is used in C++ to mark the end of all statements. #include <iostream> int main() { std::cout << "Hello World"; } Using namespace To make things a bit easier you can add a line specifying that the code file uses the standard namespace. You then no longer have to prefix cout with the namespace (std::) since it is now used by default. #include <iostream> using namespace std; int main() { cout << "Hello World"; }
📄 Page 8
3 Chapter 2 Compile and Run Visual Studio compilation Continuing from the last chapter, the Hello World program is now complete and ready to be compiled and run. You can do this by going to the Debug menu and clicking on Start Without Debugging (Ctrl + F5). Visual Studio then compiles and runs the application which displays the text in a console window. If you select Start Debugging (F5) from the Debug menu instead, the console window displaying Hello World will close as soon as the main function is finished. To prevent this you can add a call to the cin::get function at the end of main. This function, belonging to the console input stream, will read input from the keyboard until the return key is pressed. #include <iostream> using namespace std; int main() { cout << "Hello World"; cin.get(); } Console compilation As an alternative to using an IDE you can also compile source files from the command line as long as you have a C++ compiler.1 For example, on a Linux machine you can use the GNU C++ compiler, which is available on virtually all Unix systems. You type the compiler name “g++” and give it the input and output filenames as arguments. It then produces an executable, which when run gives the same result as one compiled under Windows. g++ MyApp.cpp -o MyApp.exe ./MyApp.exe Hello World 1http://www2.research.att.com/~bs/compilers.html
📄 Page 9
CHAPTER 2 ■ ComPilE And Run 4 Comments C++ has two kinds of comment notations – single-line and multi-line. These are used to insert notes into the source code and will have no effect on the end program. // single-line comment /* multi-line comment */
📄 Page 10
5 Chapter 3 Variables Variables are used for storing data during program execution. Data types Depending on what data you need to store there are several kinds of built-in data types. These are often called fundamental data types or primitives. The integer (whole number) types are short, int and long. The float, double and long double types are floating-point (real number) types. The char type holds a single character and the bool type contains either a true or false value. Data Type Size (byte) Description char 1 Integer or character short 2 int 4 Integer long 4 float 4 double 8 Floating-point number long double 8 bool 1 Boolean value In C++, the exact size and range of the data types are not fixed. Instead they are dependent on the system for which the program is compiled. The sizes shown in the table above are those found on most 32-bit systems and are given in C++ bytes. A byte in C++ is the minimum addressable unit of memory, which is guaranteed to be at least 8 bits, but might also be 16 or 32 bits depending on the system. By definition, a char in C++ is 1 byte in size. Furthermore, the int type will have the same size as the processor’s word size, so for a 32-bit system the integers will be 32 bits in size. Each integer type in the table must also be at least as large as the one preceding it. The same applies to floating-point types where each one must provide at least as much precision as the preceding one.
📄 Page 11
CHAPTER 3 ■ VARiAblEs 6 Declaring variables To declare (create) a variable you start with the data type you want the variable to hold followed by an identifier, which is the name of the variable. The name can consist of letters, numbers and underscores, but it cannot start with a number. It also cannot contain spaces or special characters and must not be a reserved keyword. int myInt; // correct int _myInt32; // correct int 32Int; // incorrect (starts with number) int Int 32; // incorrect (contains space) int Int@32; // incorrect (contains special character) int new; // incorrect (reserved keyword) Assigning variables To assign a value to a declared variable the equal sign is used, which is called the assignment operator (=). myInt = 50; The declaration and assignment can be combined into a single statement. When a variable is assigned a value it then becomes defined. int myInt = 50; At the same time that the variable is declared there is an alternative way of assigning, or initializing, it by enclosing the value in parentheses. This is known as constructor initialization and is equivalent to the statement above. int myAlt (50); If you need to create more than one variable of the same type there is a shorthand way of doing it using the comma operator (,). int x = 1, y = 2, z; Octal and hexadecimal assignment In addition to standard decimal notation, integers can also be assigned by using octal or hexadecimal notation. Both numbers below represent the same number, which in decimal notation is 50. int myOct = 062; // octal notation (0) int myHex = 0x32; // hexadecimal notation (0x)
📄 Page 12
CHAPTER 3 ■ VARiAblEs 7 Using variables Once a variable has been defined (declared and assigned) you can use it by simply referencing the variable’s name, for example to print it. std::cout << myInt << myAlt; // 5050 Variable scope Variables in C++ may be declared both globally and locally. A global variable is declared outside of any code blocks and will be accessible from anywhere after it has been declared, even in other source files in the same project. A local variable, on the other hand, is declared inside of a function and will only be accessible within that function after it has been declared. The lifetime of a local variable is also limited. A global variable will remain allocated for the duration of the program, while a local variable will be destroyed when its function has finished executing. int globalVar; // global variable int main() { int localVar; } // local variable Default values Global variables in C++ are automatically initialized to zero. Local variables however do not have this advantage. Instead, they will contain whatever garbage is left in that memory location. It is therefore a good idea to always give your local variables an initial value when they are declared. int globalVar; // initialized to 0 int main() { int localVar; } // uninitialized Integer types There are four integer types you can use depending on how large a number you need the variable to hold. char myChar = 0; // -128 to +127 short myShort = 0; // -32768 to +32767 int myInt = 0; // -2^31 to +2^31-1 long myLong = 0; // -2^31 to +2^31-1 Many C++ compilers also support the long long data type, which is guaranteed to be at least 64-bits. This data type is included in the Microsoft C++ compiler. long long myL2 = 0; // -2^63 to +2^63-1
📄 Page 13
CHAPTER 3 ■ VARiAblEs 8 To determine the exact size of a data type you can use the sizeof operator. This operator returns the number of bytes that a data type occupies in the system you are compiling for. std::cout << sizeof(myChar) // 1 byte (per definition) << sizeof(myShort) // 2 << sizeof(myInt) // 4 << sizeof(myLong) // 4 << sizeof(myL2); // 8 The Microsoft C++ compiler features five sized integer types. These types start with __int followed by the number of bits you want the integer to hold – either 8, 16, 32 or 64 bits. __int8 myInt8 = 0; // 8 bits __int16 myInt16 = 0; // 16 bits __int32 myInt32 = 0; // 32 bits __int64 myInt64 = 0; // 64 bits Signed and unsigned integers By default, all the number types in Microsoft C++ are signed and may therefore contain both positive and negative values. To explicitly declare a variable as signed the signed keyword can be used. signed char myChar = 0; // -128 to +127 signed short myShort = 0; // -32768 to +32767 signed int myInt = 0; // -2^31 to +2^31-1 signed long myLong = 0; // -2^31 to +2^31-1 signed long long myL2= 0; // -2^63 to +2^63-1 If you only need to store positive values you can declare integer types as unsigned to double their upper range. unsigned char myChar = 0; // 0 to 255 unsigned short myShort = 0; // 0 to 32767 unsigned int myInt = 0; // 0 to 2^32-1 unsigned long myLong = 0; // 0 to 2^32-1 unsigned long long myL2= 0; // 0 to 2^64-1 The signed and unsigned keywords may be used as standalone types, which are short for signed int and unsigned int. unsigned uInt; // unsigned int signed sInt; // signed int Similarly, the short and long data types are abbreviations of short int and long int. short myShort; // short int long myLong; // long int
📄 Page 14
CHAPTER 3 ■ VARiAblEs 9 Floating-point types The floating-point types can store real numbers with different levels of precision. float myFloat = 3.14; // 3.4E +/- 38 (7 digits) double myDouble = 3.14; // 1.7E +/- 308 (15 digits) long double myLongDouble = 3.14; // same as double The precision shown above refers to the total number of digits in the number. For example, trying to assign more than 7 digits to a float means that the least significant digits will get rounded off. myFloat = 12345.678; // rounded to 12345.68 Floats and doubles can be assigned by using either decimal or exponential notation. myFloat = 3e2; // 3*10^2 = 300 Char type The char type is commonly used to represent ASCII characters. char c = 'x'; // assigns 120 (ASCII for 'x') The conversion between the number stored in the char and the character shown when the char is printed occurs automatically. std::cout << c; // prints 'x' For another integer type to be displayed as a character it has to be explicitly cast to char. An explicit cast is performed by placing the desired data type in parentheses before the variable or constant that is to be converted. int i = c; // assigns 120 std::cout << i; // prints 120 std::cout << (char)i; // prints 'x' Bool type The bool type can store a Boolean value, which is a value that can only be either true or false. These values are specified with the true and false keywords. bool b = false; // true or false value
📄 Page 15
11 Chapter 4 Operators The numerical operators in C++ can be grouped into five types: arithmetic, assignment, comparison, logical and bitwise operators. Arithmetic operators There are the four basic arithmetic operators, as well as the modulus operator (%) which is used to obtain the division remainder. x = 3 + 2; // 5 // addition x = 3 - 2; // 1 // subtraction x = 3 * 2; // 6 // multiplication x = 3 / 2; // 1 // division x = 3 % 2; // 1 // modulus (division remainder) Notice that the division sign gives an incorrect result. This is because it operates on two integer values and will therefore truncate the result and return an integer. To get the correct value one of the numbers must be explicitly converted to a floating-point number. x = 3 / (float)2; // 1.5 Assignment operators The second group is the assignment operators. Most importantly, the assignment operator (=) itself, which assigns a value to a variable. Combined assignment operators A common use of the assignment and arithmetic operators is to operate on a variable and then to save the result back into that same variable. These operations can be shortened with the combined assignment operators.
📄 Page 16
CHAPTER 4 ■ OPERATORs 12 x += 5; // x = x+5; x -= 5; // x = x-5; x *= 5; // x = x*5; x /= 5; // x = x/5; x %= 5; // x = x%5; Increment and decrement operators Another common operation is to increment or decrement a variable by one. This can be simplified with the increment (++) and decrement (--) operators. x++; // x = x+1; x--; // x = x-1; Both of these can be used either before or after a variable. x++; // post-increment x--; // post-decrement ++x; // pre-increment --x; // pre-decrement The result on the variable is the same whichever is used. The difference is that the post-operator returns the original value before it changes the variable, while the pre-operator changes the variable first and then returns the value. x = 5; y = x++; // y=5, x=6 x = 5; y = ++x; // y=6, x=6 Comparison operators The comparison operators compare two values and return either true or false. They are mainly used to specify conditions, which are expressions that evaluate to either true or false. bool x = (2 == 3); // false // equal to x = (2 != 3); // true // not equal to x = (2 > 3); // false // greater than x = (2 < 3); // true // less than x = (2 >= 3); // false // greater than or equal to x = (2 <= 3); // true // less than or equal to Logical operators The logical operators are often used together with the comparison operators. Logical and (&&) evaluates to true if both the left and right sides are true, and logical or (||) is true if either the left or right side is true. For inverting a Boolean result there is the logical not (!)
📄 Page 17
CHAPTER 4 ■ OPERATORs 13 operator. Note that for both “logical and” and “logical or” the right-hand side will not be evaluated if the result is already determined by the left-hand side. bool x = (true && false); // false // logical and x = (true || false); // true // logical or x = !(true); // false // logical not Bitwise operators The bitwise operators can manipulate individual bits inside an integer. For example, the “bitwise or” operator (|) makes the resulting bit 1 if the bits are set on either side of the operator. int x = 5 & 4; // 101 & 100 = 100 (4) // and x = 5 | 4; // 101 | 100 = 101 (5) // or x = 5 ^ 4; // 101 ^ 100 = 001 (1) // xor x = 4 << 1; // 100 << 1 =1000 (8) // left shift x = 4 >> 1; // 100 >> 1 = 10 (2) // right shift x = ~4; // ~00000100 = 11111011 (-5) // invert The bitwise operators also have combined assignment operators. int x=5; x &= 4; // 101 & 100 = 100 (4) // and x=5; x |= 4; // 101 | 100 = 101 (5) // or x=5; x ^= 4; // 101 ^ 100 = 001 (1) // xor x=5; x <<= 1;// 101 << 1 =1010 (10)// left shift x=5; x >>= 1;// 101 >> 1 = 10 (2) // right shift Operator precedence In C++, expressions are normally evaluated from left to right. However, when an expression contains multiple operators, the precedence of those operators decides the order that they are evaluated in. The order of precedence can be seen in the table below. This same order also applies to many other languages, such as Java and C#. Pre Operator Pre Operator 1 ++ -- ! ~ 7 & 2 * / % 8 ^ 3 + - 9 | 4 << >> 10 && 5 < <= > >= 11 || 6 == != 12 = op=
📄 Page 18
CHAPTER 4 ■ OPERATORs 14 For example, logical and (&&) binds weaker than relational operators, which in turn bind weaker than arithmetic operators. bool x = 2+3 > 1*4 && 5/5 == 1; // true To make things clearer, parentheses can be used to specify which part of the expression will be evaluated first. Parentheses have the highest precedence of all operators. bool x = ((2+3) > (1*4)) && ((5/5) == 1); // true
📄 Page 19
15 Chapter 5 Pointers A pointer is a variable that contains the memory address of another variable, called the pointee. Creating pointers Pointers are declared as any other variable, except that an asterisk (*) is placed between the data type and the pointer’s name. The data type used determines what type of memory it will point to. int* p; // pointer to an integer int *q; // alternative syntax A pointer can point to a variable of the same type by prefixing that variable with an ampersand, in order to retrieve its address and assign it to the pointer. The ampersand is known as the address-of operator (&). int i = 10; p = &i; // address of i assigned to p Dereferencing pointers The pointer above now contains the memory address to the integer variable. Referencing the pointer will retrieve this address. To obtain the actual value stored in that address the pointer must be prefixed with an asterisk, known as the dereference operator (*). std::cout << "Address of i: " << p; // ex. 0017FF1C std::cout << "Value of i: " << *p; // 10 When writing to the pointer, the same method is used. Without the asterisk the pointer is assigned a new memory address, and with the asterisk the actual value of the variable pointed to will be updated. p = &i; // address of i assigned to p *p = 20; // value of i changed through p
📄 Page 20
CHAPTER 5 ■ PoinTERs 16 If a second pointer is created and assigned the value of the first pointer it will then get a copy of the first pointer’s memory address. int* p2 = p; // copy of p (copies address stored in p) Pointing to a pointer Sometimes it can be useful to have a pointer that can point to another pointer. This is done by declaring a pointer with two asterisks and then assigning it the address of the pointer that it will reference. This way when the address stored in the first pointer changes, the second pointer can follow that change. int** r = &p; // pointer to p (assigns address of p) Referencing the second pointer now gives the address of the first pointer. Dereferencing the second pointer gives the address of the variable and dereferencing it again gives the value of the variable. std::cout << "Address of p: " << r; // ex. 0017FF28 std::cout << "Address of i: " << *r; // ex. 0017FF1C std::cout << "Value of i: " << **r; // 20 Dynamic allocation One of the main usages of pointers is to allocate memory during run-time – so called dynamic allocation. In the examples so far, the programs have only had as much memory available as has been declared for the variables at compile-time. This is referred to as static allocation. If any additional memory is needed at run-time, the new operator has to be used. This operator allows for dynamic allocation of memory, which can only be accessed through pointers. The new operator takes either a primitive data type or an object as its argument, and it will return a pointer to the allocated memory. int* d = new int; // dynamic allocation An important thing to know about dynamic allocation is that the allocated memory will not be released like the rest of the program memory when it is no longer required. Instead, it has to be manually released with the delete keyword. This allows you to control the lifetime of a dynamically allocated object, but it also means that you are responsible for deleting it once it is no longer needed. Forgetting to delete memory that has been allocated with the new keyword will give the program memory leaks, because that memory will stay allocated until the program shuts down. delete d; // release allocated memory
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List