Академический Документы
Профессиональный Документы
Культура Документы
Program at developer.redhat.com/rhel.
Copyright © 2013 Red Hat, Inc. Red Hat, Red Hat Enterprise Linux, the Shadowman logo, and JBoss are trademarks of Red Hat, Inc., registered in the U.S. and
other countries. Linux® is the registered trademark of Linus Torvalds in the U.S. and other countries.
DZone, Inc. | www.dzone.com
Brought to you by:
#189
Get More Refcardz! Visit refcardz.com
Core C++
CONTENTS INCLUDE:
❱ C++ Types and Modifiers
❱ Namespaces
❱ Operator Precedence
❱ Pre-Processor Directives
❱ Class Definition
❱ Parameter Passing... and More! By: Steve Oualline
compilers.)
Learn. Code. Share.
mutable Indicate a member variable that may be modified even in a
const instance of a class Copyright © 2013 Red Hat, Inc. Red Hat, Red Hat Enterprise Linux, the Shadowman logo, and JBoss are trademarks of Red Hat, Inc.,
registered in the U.S. and other countries. Linux® is the registered trademark of Linus Torvalds in the U.S. and other countries.
Pointers, like variables, can be declared constant. The value can also be de- Precedence Operator Description
clared constant. Both can be declared constant at the same time, like this: 1 :: scope resolution
char* foo; Pointer can be modified. Data can be modified. ++ -- suffix increment/decrement
const char* foo; Pointer can be modified. Data can be not modified. () function call
char* const foo; Pointer can be not modified. Data can be modified. 2 [] array subscripting
const char* const foo; Pointer can be not modified. Data can not be . element selection (reference)
modified.
-> element selection (pointer)
#include "file" Include a local header file in the program 14 && logical AND
#define NAME value Define a macro. (In most cases a const 15 || logical OR
declaration is better than a #define.)
16 ?: ternary conditional
Note: When the value is an expression, it is a good idea to put parentheses
= direct assignment
around the entire value, e.g.: #define AREA (width * height)
+= -+ assignment by sum/difference
#define MACRO(p1, p2) \ Define a parameterized macro. (In almost
value all cases creating an inline function is 17 *= /= %= assignment by product/quotient/remainder
preferable to a parameterized macro.)
<<= >>= assignment by bitwise shift left/right
Note: It is a good idea to put () around the parameters when defining a
&= ^= |= assignment by bitwise AND/OR/XOR
macro, e.g.: #define SQUARE(x) ((x) * (x))
size = square(3+5) 18 throw throw (exception)
#undef NAME Undefine a previously defined macro 19 , comma
#ifdef NAME Compile the following code if NAME is
defined
Function Declaration
#ifndef NAME Compile the following code if NAME is not
defined The basic format of a function is:
#else Reverse the previous #ifdef, #ifndef, or #if
type name ( parameter1, parameter2, ...) { statements }
#endif End of a #ifdef, #ifndef, or #if block
#if <expression> Compile the following code if the
Type Indicates
expression is true
void Indicates a function that does not return a value.
#error Message Raise a compile time error
void resetAll() {...}
#warning Message Raise a compile time warning
static Scope declaration (see variable modifiers above)
#line <line-info> Synchronize line counters. Used by static int getDate(void) {...}
programs that produce C++ code so that
inline A hint to the compiler, telling it that this function is small
the compiler can issue error message
enough that body of the code for this function can be inserted
using the original file's line number.
inline rather than using the normal call / return instruction
#pragma <system- Used for compiler dependent settings and sequence.
dependent> operations static inline square(const int x)
{ return (x*x); }
extern Function that may be defined in another compilation unit.
extern int getTime(void);
Pass by value: the default way of passing. Changes to parameter are not funct(array) //equivalent to
passed back to the calling code. funct(&array[0])
Default Arguments
Arguments at the end of the arguments list can have default values, The public, private, and protected members sections may be repeated as
assigned like this: many times as needed.
va_arg(n, type) Get an argument from the list mutable A member that may be changed even if the class cannot
va_end Indicate that argument processing is complete const (After function definition) -- A member function that can be
called in a constant instance of the class
Definitions for variable argument lists are in the header file cstdarg. Here’s explicit A constructor that must be explicitly specified. Prevents
how that works out in code: automatic type conversions during initialization.
#include <cstdarg> virtual Indicate a member function that can be overridden by a
derived class that uses this one as a base.
void funct(int num, ... )
{ virtual = 0 Pure virtual function. A member function that must be
va_list arg_list;
overridden by a derived class.
va_start(arg_list, num);
int i = va_arg (arg_list, int);
int j = va_arg(arg_list, double);
va_end(arg_list);
}
class derived: protected base std::right Right justify output by padding the
left side
Only classes derived from derived can access base. std::dec Output numbers in decimal format
std::hex Output numbers in hexadecimal
class derived: private base format
I/O Flags
The rest of this card collects information on some of the most common std::ios::boolalpha If set, write boolean values as
methods for output stream manipulation, with special focus on strings. characters
(For a similar treatment of Java, see the Core Java Refcard: http://refcardz.
dzone.com/refcardz/core-java). Some of the objects mentioned (e.g. std::ios::showbase Write a prefix to show the base (hex,
iterators) can also be used with other data types. octal, decimal) being output
std::ios::showpoint Output floating point numbers with a
decimal point
Output stream manipulation
std::ios::showpos Put a "+" in front of positive values
std::ios::skipws Skip whitespace on input
std::endl Writes a newline and flushes output
std::ios::unitbuf Flush output after each unit is
std::ends Writes a null character ('\0') and
written
flushes output
std::ios::uppercase Use upper case letters for numerical
std::flush Flushes output
output (1E33, 0xABC)
std::resetiosflags(ios_base::fmtflags Reset the given ioflags (see below)
std::ios::dec Output numbers in decimal format
mask)
std::ios::hex Output numbers in hexadecimal
std::setiosflags (ios_base::fmtflags Set the given ioflags (see below)
format
mask)
std::ios::oct Output numbers in octal format
std::setbase(int base) Set the base for output conversion
std::ios::fixed Output floating point numbers in
std::setfill(char c) Set the fill character
fixed format
std::setprecision(int n) Set the precision for floating point
std::ios::scientific Output floating point numbers in
output
floating point format
std::setw(int n) Set the width for numeric output
std::ios::internal Pad by adding the fill character
std::boolalpha Print true and false as characters between the sign and the number
std::noboolalpha Print true and false as 1 and 0 std::ios::left Left justify the output
std::showbase Print a prefix (0x or 0) for std::ios::right Right justify the output
hexadecimal or octal numbers
Constructors and Assignment char at(size_type pos) Return the character at the given
position. If there is no such
string() Construct an empty string character, throw an std::out_of_range
error.
string(std::string& str) Copy constructor. Copies initial
value from an existing string. operator += (std::string& str) Append a string on to this one
string(std::string& str, size_type Initialize with substring of str operator += (const char* c_str) Append a C style string to this string
pos) starting at pos
operator += (char ch) Append a character to this string
string(std::string& str, size_type pos, Initialize with an initial substring
size_type length) of str starting at pos and going for append(std::string str) Append a string to this one
length characters append(std::string str, size_type Append a substring of str to this one
string(const char* const c_str) Initialize with a C style string pos, size_type n)
string(const char* const c_str, Initialize with the first len characters append(const char* const c_str) Append a C style string to this one
size_type len) from a C style string append(const char* const c_str, Append a C style string to this one
string(size_type count, char ch) Create a string by repeating ch size_type len) with limited length
count times append(size_type count, char ch) Append a string consisting of
string(iterator begin, iterator end) Create a string by copying the string repeating ch count times
between the two iterators starting at append(iterator first, iterator last) Append a string specified by iterators
begin and ending just before end to this one
operator = (const std::string str) Assignment operator push_back(char ch) Append a single character to the
operator = (const char* const c_str) C style string, assignment operator string
assign(std::string str) Replace the string with a new one
operator = (char ch) Single character assignment
assign(std::string size_type pos, Assign this string the value of the
size_type length) given substring
Other Member Functions
assign(const char* const c_str) Replace the string with the given C
iterator begin() Return an iterator pointing to the first style string
character of the string
assign(const char* const c_str, Replace the string with the given C
const_iterator begin() const Return a const_iterator pointing to the size_type length) style string with limited length
first character of the string
assign(size_type count, char ch) Replace the string with one iterator erase(iterator where) Erase one character. Returns the
containing ch repeated count times iterator where which points to the
character after the erasure.
assign(iterator begin, iterator end) Assign the string the value of the
string delimited by the iterators iterator = erase(iterator start, Erase from first to just before last.
iterator last) Returns the location of the character
insert(iterator where, iterator begin, Insert string specified by begin, end
just after the last removal.
iterator end) just before where
string = replace(size_type where, Replace characters starting at where
insert(size_type where, const Insert the given string just before
size_type length, const std::string& and continuing for length with the
std::string& str) where
str) given replacement string. Returns a
insert(size_type where, const Insert the given string starting at start reference to the new string.
std::string& str, size_type start, and going for length characters just
string = replace(size_type where, Replace characters starting at where
size_type length) before where
size_type length, const std::string& and continuing for length with the
insert(size_type where, const char* Insert the C style string just before c_str, size_type replace_where, given replacement string starting at
const c_str) where size_type replace_length) replace_where for replace_length.
Returns a reference to the new string.
insert(size_type where, const char* Insert the C style string for length
const c_str, size_type length) characters just before the position
where
additional resources
insert(size_type where, size_type Insert a string made of ch characters
count, char ch) repeated count times just before
where • Standard Template Library: http://www.cplusplus.com/reference/stl/
insert(iterator where, char ch) Insert a single character just before
where. After all of the above, it hardly • GNU Compiler Collection: http://gcc.gnu.org/
seems worth it.
• C++ spec (working draft): http://www.open-std.org/jtc1/sc22/wg21/
string = erase() Erase the entire string. Returns a
docs/papers/2011/n3242.pdf
reference to the string.
string = erase(size_type pos) Erase the string from pos to the end. • Standard C++ Foundation (director is Bjarne Stroustrup):
Returns a reference to the string. http://isocpp.org/
string = erase(size_type pos, Erase the string from pos for length
size_type length) characters. Returns a reference to • General C++ forum (very active):
the string. http://www.cplusplus.com/forum/general/
A B O U T t h e A ut h or R ecomme n ded B oo k
C++ is extremely powerful, and experienced C++
Steve Oualline has been programming for more than 45
programmers can develop complex applications
years. He is the author of numerous books, including
very efficiently. But mapping generic object-
“Practical C++ Programming”, “How Not to Program in
oriented programming ability, on the one hand, or
C++”, and “Wicked Cool Perl”. Currently he works as a
facility with C, on the other, to the complexities of
programmer for Linear Corp. and spends his spare time
C++, can be difficult. This book covers all aspects
playing with the trains at the Orange Empire Railroad
of C++ programming, from software engineering
Museum.
to debugging, to common mistakes and how to fix
them.
BUY NOW
Free PDF
Ruby on Rails
Regex
Clean Code
Python
DZone, Inc.
150 Preston Executive Dr.
Suite 201
Cary, NC 27513
DZone communities deliver over 6 million pages each month to 888.678.0399
more than 3.3 million software developers, architects and decision 919.678.0300
makers. DZone offers something for everyone, including news,
Refcardz Feedback Welcome
$7.95
tutorials, cheat sheets, blogs, feature articles, source code and more.
“"DZone is a developer's dream",” says PC Magazine. refcardz@dzone.com
Copyright © 2013 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval Sponsorship Opportunities
system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
sales@dzone.com
Version 1.0
written permission of the publisher.