Anda di halaman 1dari 22

asm The __asm __asm {

mov al, 2
keyword invokes
mov dx, 0xD007
the inline out dx, al
assembler and can }
appear wherever a
C or C++ __asm mov al, 2
statement is legal. __asm mov dx, 0xD007
__asm out dx, al
It cannot appear by
itself. It must be
followed by an
assembly
instruction, a
group of
instructions
enclosed in braces,
or, at the very
least, an empty
pair of braces. The
term "__asm
block" here refers
to any instruction
or group of
instructions,
whether or not in
braces.
Dynamic_cast Converts the // dynamic_cast_8.cpp
// compile with: /GR /EHsc
operand
#include <stdio.h>
expression to an #include <iostream>
object of type
type-id. struct A {
virtual void test() {
printf_s("in A\n");
}
};

struct B : A {
virtual void test() {
printf_s("in B\n");
}

void test2() {
printf_s("test2 in B\n");
}
};

struct C : B {
virtual void test() {
printf_s("in C\n");
}
void test2() {
printf_s("test2 in C\n");
}
};

void Globaltest(A& a) {
try {
C &c = dynamic_cast<C&>(a);
printf_s("in GlobalTest\n");
}
catch(std::bad_cast) {
printf_s("Can't cast to C\n");
}
}

int main() {
A *pa = new C;
A *pa2 = new B;

pa->test();

B * pb = dynamic_cast<B *>(pa);
if (pb)
pb->test2();

C * pc = dynamic_cast<C *>(pa2);
if (pc)
pc->test2();

C ConStack;
Globaltest(ConStack);

// will fail because B knows nothing


about C
B BonStack;
Globaltest(BonStack);
}

delete The cast- int* set = new int[100];


//use set[]
expression delete [] set;
argument must be
a pointer to a block CDialog* MyDialog = new CDialog;
of memory // use MyDialog
previously delete MyDialog;
allocated for an
object created with
the new operator.
The delete
operator has a
result of type void
and therefore does
not return a value.
virtual The virtual virtual [type-specifiers] member-
function-declarator
keyword declares a
virtual [access-specifier] base-class-
virtual function or name
a virtual base
class.
using The using // using_declaration1.cpp
#include <stdio.h>
declaration
class B {
introduces a name public:
into the declarative void f(char) {
region in which printf_s("In B::f()\n");
the using }
declaration void g(char) {
appears. printf_s("In B::g()\n");
}
};

class D : B {
public:
using B::f;
using B::g;
void f(int) {
printf_s("In D::f()\n");
f('c');
}

void g(int) {
printf_s("In D::g()\n");
g('c');
}
};

int main() {
D myD;
myD.f(1);
myD.g('a');
}

typename Tells the compiler // typename.cpp


template<class T> class X
that an unknown
{
identifier is a type. typename T::Y m_y; // treat Y as a
This keyword must type
be used if the };
name is a qualified
int main()
name dependent {
on a template }
argument; it is
optional if the
qualified name is
not dependent.
typeid typeid is similar to // keyword__typeid.cpp
// compile with: /clr
getting the System using namespace System;
However, typeid
ref struct G {
only accepts a type int i;
name as a };
parameter. If you
want to use an int main() {
G ^ pG = gcnew G;
instance of a type Type ^ pType = pG->GetType();
to get its Type ^ pType2 = G::typeid;
System::Type
name, use if (pType == pType2)
GetType. Console::WriteLine("typeid and
GetType returned the same
System::Type");
Console::WriteLine(G::typeid);

typedef float* FloatPtr;

Console::WriteLine(FloatPtr::typeid);
}

try The following //


exceptions_trycatchandthrowstatements2.
syntax shows a try
cpp
block and its // compile with: /EHsc
handlers #include <iostream>
using namespace std;
void MyFunc( void );

class CTest {
public:
CTest() {};
~CTest() {};
const char *ShowReason() const {
return "Exception in CTest
class.";
}
};

class CDtorDemo {
public:
CDtorDemo();
~CDtorDemo();
};

CDtorDemo::CDtorDemo() {
cout << "Constructing CDtorDemo.\n";
}

CDtorDemo::~CDtorDemo() {
cout << "Destructing CDtorDemo.\n";
}

void MyFunc() {
CDtorDemo D;
cout<< "In MyFunc(). Throwing CTest
exception.\n";
throw CTest();
}

int main() {
cout << "In main.\n";
try {
cout << "In try block, calling
MyFunc().\n";
MyFunc();
}
catch( CTest E ) {
cout << "In catch handler.\n";
cout << "Caught CTest exception
type: ";
cout << E.ShowReason() << "\n";
}
catch( char *str ) {
cout << "Caught some other
exception: " << str << "\n";
}
cout << "Back in main. Execution
resumes here.\n";
}

true This keyword is // bool_true.cpp


#include <stdio.h>
one of the two
int main()
values for a {
variable of type bool bb = true;
bool or a printf_s("%d\n", bb);
conditional bb = false;
printf_s("%d\n", bb);
expression (a }
conditional
expression is now
a true boolean
expression). If i is
of type bool, then
the statement i =
true; assigns true
to i.
this The this pointer is // this_pointer.cpp
// compile with: /EHsc
a pointer
accessible only #include <iostream>
within the #include <string.h>
nonstatic member
functions of a using namespace std;
class, struct, or class Buf
union type. It {
points to the object public:
for which the Buf( char* szBuffer, size_t
member function sizeOfBuffer );
Buf& operator=( const Buf & );
is called. Static
void Display() { cout << buffer <<
member functions endl; }
do not have a this
pointer. private:
char* buffer;
size_t sizeOfBuffer;
};

Buf::Buf( char* szBuffer, size_t


sizeOfBuffer )
{
sizeOfBuffer++; // account for a
NULL terminator

buffer = new char[ sizeOfBuffer ];


if (buffer)
{
strcpy_s( buffer, sizeOfBuffer,
szBuffer );
sizeOfBuffer = sizeOfBuffer;
}
}

Buf& Buf::operator=( const Buf


&otherbuf )
{
if( &otherbuf != this )
{
if (buffer)
delete [] buffer;

sizeOfBuffer =
strlen( otherbuf.buffer ) + 1;
buffer = new
char[sizeOfBuffer];
strcpy_s( buffer, sizeOfBuffer,
otherbuf.buffer );
}
return *this;
}

int main()
{
Buf myBuf( "my buffer", 10 );
Buf yourBuf( "your buffer", 12 );

// Display 'my buffer'


myBuf.Display();

// assignment opperator
myBuf = yourBuf;

// Display 'your buffer'


myBuf.Display();
}
template The template //
references__supported_as_nontype_templa
declaration te_parameters.cpp
specifies a set of #include <stdio.h>
parameterized
classes or extern "C" int printf_s(const
functions. char*,...);
template <int & ri> struct S
{
The template- S()
parameter-list is a {
comma-separated printf_s("ri is %d\n", ri);
list of template }
parameters, which ~S()
may be types (in {
the form printf_s("ri is %d\n", ri);
classidentifier, }
};
typenameidentifie
r, or template < int i = 1;
template-
parameter-list > int main()
class identifier) or {
S<i> s;
non-type i = 0;
parameters to be }
used in the
template body.
The syntax for a
// template_specifications4.cpp
template parameter
is one of the template <typename T>
following: class A
{
};

template <int n>


class B
{
};

int main()
{
A<B<22>>();
}

Static_cast Converts // static_cast_Operator_3.cpp


// compile with: /LD /GR
expression to the
typedef unsigned char BYTE;
type of type-id
based solely on the void f() {
types present in char ch;
the expression. int i = 65;
float f = 2.5;
double dbl;

ch = static_cast<char>(i); // int
to char
dbl = static_cast<double>(f); //
float to double
i = static_cast<BYTE>(ch);
}

Reinterpret_cast Allows any pointer // expre_reinterpret_cast_Operator.cpp


// compile with: /EHsc
to be converted #include <iostream>
into any other
pointer type. // Returns a hash code based on an
address
The unsigned short Hash( void *p ) {
unsigned int val =
reinterpret_cast reinterpret_cast<unsigned int>( p );
operator also return ( unsigned short )( val ^
allows any integral (val >> 16));
type to be }
converted into any
using namespace std;
pointer type and int main() {
vice versa. Misuse int a[20];
of the for ( int i = 0; i < 20; i++ )
reinterpret_cast cout << Hash( a + i ) << endl;
}
operator can easily
be unsafe. Unless
the desired
conversion is
inherently low-
level, you should
use one of the
other cast
operators.
protected The protected // keyword_protected.cpp
// compile with: /EHsc
keyword specifies #include <iostream>
access to class
members in the using namespace std;
member-list up to class X {
the next access public:
void setProtMemb( int i )
specifier (public { m_protMemb = i; }
or private) or the void Display() { cout << m_protMemb
end of the class << endl; }
definition. protected:
int m_protMemb;
void Protfunc() { cout << "\nAccess
allowed\n"; }
} x;

class Y : public X {
public:
void useProtfunc() { Protfunc(); }
} y;

int main() {
// x.m_protMemb; error,
m_protMemb is protected
x.setProtMemb( 0 ); // OK, uses
public access function
x.Display();
y.setProtMemb( 5 ); // OK, uses
public access function
y.Display();
// x.Protfunc(); error,
Protfunc() is protected
y.useProtfunc(); // OK, uses
public access function
// in derived
class
}

public When preceding a // keyword_public.cpp


class BaseClass {
list of class public:
members, the int pubFunc() { return 0; }
public keyword };
specifies that those
members are class DerivedClass : public BaseClass
{};
accessible from
any function. This int main() {
applies to all BaseClass aBase;
members declared DerivedClass aDerived;
up to the next aBase.pubFunc(); // pubFunc()
is accessible
access specifier or // from
the end of the any function
class. aDerived.pubFunc(); // pubFunc()
is still public in
// derived
When preceding class
the name of a base }
class, the public
keyword specifies
that the public and
protected members
of the base class
are public and
protected
members,
respectively, of the
derived class.

Default access of
members in a class
is private. Default
access of members
in a structure or
union is public.
private When preceding a // keyword_private.cpp
class BaseClass {
list of class
public:
members, the // privMem accessible from member
private keyword function
specifies that those int pubFunc() { return privMem; }
members are private:
void privMem;
accessible only };
from member
functions and class DerivedClass : public BaseClass {
friends of the public:
class. This applies void usePrivate( int i )
{ privMem = i; } // C2248:
to all members privMem not accessible
declared up to the // from
next access derived class
specifier or the end };
of the class. class DerivedClass2 : private BaseClass
{
When preceding public:
the name of a base // pubFunc() accessible from derived
class, the private class
int usePublic() { return
keyword specifies pubFunc(); }
that the public and };
protected members
of the base class int main() {
are private BaseClass aBase;
DerivedClass aDerived;
members of the DerivedClass2 aDerived2;
derived class. aBase.privMem = 1; // C2248:
privMem not accessible
aDerived.privMem = 1; // C2248:
privMem not accessible
// in
derived class
aDerived2.pubFunc(); // C2247:
pubFunc() is private in
// derived
class
}

operator The operator // operator_overloading.cpp


// compile with: /EHsc
keyword declares a
#include <iostream>
function using namespace std;
specifying what
operator-symbol struct Complex {
means when Complex( double r, double i ) :
re(r), im(i) {}
applied to
Complex operator+( Complex &other );
instances of a void Display( ) { cout << re << ",
class. This gives " << im << endl; }
the operator more private:
than one meaning, double re, im;
};
or "overloads" it.
The compiler // Operator overloaded using a member
distinguishes function
between the Complex Complex::operator+( Complex
different meanings &other ) {
return Complex( re + other.re, im +
of an operator by other.im );
examining the }
types of its
operands. int main() {
Complex a = Complex( 1.2, 3.4 );
Complex b = Complex( 5.6, 7.8 );
Complex c = Complex( 0.0, 0.0 );

c = a + b;
c.Display();
}

new In a /clr // newslot.cpp


// compile with: /clr
compilation, new
ref class C {
indicates that a public:
virtual member virtual void f() {
will get a new slot
in the vtable; that System::Console::WriteLine("C::f()
called");
the function does }
not override a base
class method. virtual void g() {

new causes the System::Console::WriteLine("C::g()


called");
newslot modifier }
to be added to the };
IL for the function.
ref class D : public C {
public:
virtual void f() new {

System::Console::WriteLine("D::f()
called");
}

virtual void g() override {

System::Console::WriteLine("D::g()
called");
}
};

ref class E : public D {


public:
virtual void f() override {

System::Console::WriteLine("E::f()
called");
}
};

int main() {
D^ d = gcnew D;
C^ c = gcnew D;

c->f(); // calls C::f


d->f(); // calls D::f

c->g(); // calls D::g


d->g(); // calls D::g

D ^ e = gcnew E;
e->f(); // calls E::f
}

namespace A namespace 1. // namespace_declaration1.cpp


namespace X
declaration {
identifies and int i;
assigns a unique double j;
name to a user- }
declared int main()
{
namespace. X::i++;
}
Such namespaces
are used to solve
the problem of 2. // namespace_declaration2.cpp
// C2870 expected
name collision in namespace A
large programs and {
libraries. int j = 3;
Programmers can int f(int k);
}
use namespaces to
develop new namespace Outer
software {
components and int n = 6;
libraries without int func(int num);
causing naming namespace Inner
conflicts with {
existing float f = 9.993;
components. }
}
int main()
{
namespace local // C2870: not at
global scope
{
}
}

mutable This keyword can // mutable.cpp


class X
only be applied to
{
non-static and non- public:
const data bool GetFlag() const
members of a {
class. If a data m_accessCount++;
return m_flag;
member is }
declared mutable, private:
then it is legal to bool m_flag;
assign a value to mutable int m_accessCount;
this data member };
from a const int main()
member function. {
}

inline The inline and 1. // inline_keyword1.cpp


// compile with: /c
__inline specifiers
inline int max( int a , int b ) {
instruct the if( a > b )
compiler to insert return a;
a copy of the return b;
function body into }
each place the
function is called. 2. // inline_keyword2.cpp
// compile with: /EHsc /c
#include <iostream>
using namespace std;

class MyClass {
public:
void print() { cout << i << ' '; }
// Implicitly inline
private:
int i;
};

friend In some
1. friend class-name;
circumstances, it is
friend function-declarator;
more convenient to
grant member- 2. #include
level access to class exforsys
functions that are {
not members of a private:
class or to all int a,b;
public:
functions in a
void test()
separate class. {
a=100;
The friend b=200;
keyword allows a }
friend int compute(exforsys e1)
function or class to
gain access to the
//Friend Function Declaration with keyword friend and
private and with the object of class exforsys to which it is friend
protected members passed to it
of a class. };

int compute(exforsys e1)


{
//Friend Function Definition which has access to
private data
return int(e1.a+e2.b)-5;
}

main()
{
exforsys e;
e.test();
cout<<"The result is:"<
//Calling of Friend Function with object as argument.
}

false The keyword is // bool_false.cpp


#include <stdio.h>
one of the two
values for a int main()
variable of type {
bool or a bool bb = true;
conditional printf_s("%d\n", bb);
bb = false;
expression (a printf_s("%d\n", bb);
conditional }
expression is now
a true Boolean
expression). For
example, if i is a
variable of type
bool, the i =
false; statement
assigns false to i.
explicit This keyword is a // spec1_explicit.cpp
// compile with: /EHsc
declaration #include <stdio.h>
specifier that can
only be applied to class C
in-class {
public:
constructor
int i;
declarations. An explicit C(const C&) // an
explicit explicit copy constructor
constructor cannot {
take part in printf_s("\nin the copy
constructor");
implicit }
conversions. It can explicit C(int i ) // an explicit
only be used to constructor
explicitly construct {
an object. printf_s("\nin the
constructor");
}

C()
{
i = 0;
}
};

class C2
{
public:
int i;
explicit C2(int i ) // an
explicit constructor
{
}
};

C f(C c)
{ // C2558
c.i = 2;
return c; // first call to copy
constructor
}

void f2(C2)
{
}

void g(int i)
{
f2(i); // C2558
// try the following line instead
// f2(C2(i));
}

int main()
{
C c, d;
d = f(c); // c is copied
}
Const_cast Removes the // expre_const_cast_Operator.cpp
// compile with: /EHsc
const, volatile,
#include <iostream>
and __unaligned
attribute(s) from a using namespace std;
class. class CCTest {
public:
void setNumber( int );
A pointer to any void printNumber() const;
object type or a private:
pointer to a data int number;
member can be };
explicitly
void CCTest::setNumber( int num )
converted to a type { number = num; }
that is identical
except for the void CCTest::printNumber() const {
const, volatile, cout << "\nBefore: " << number;
const_cast< CCTest * >( this )-
and __unaligned >number--;
qualifiers. For cout << "\nAfter: " << number;
pointers and }
references, the
result will refer to int main() {
CCTest X;
the original object. X.setNumber( 8 );
For pointers to X.printNumber();
data members, the }
result will refer to
the same member
as the original
(uncast) pointer to
data member.
class The class keyword // class.cpp
// compile with: /EHsc
declares a class
// Example of the class keyword
type or defines an // Exhibits polymorphism/virtual
object of a class functions.
type.
#include <iostream>
#include <string>
#define TRUE = 1
using namespace std;

class dog
{
public:
dog()
{
_legs = 4;
_bark = true;
}

void setDogSize(string dogSize)


{
_dogSize = dogSize;
}
virtual void setEars(string type)
// virtual function
{
_earType = type;
}

private:
string _dogSize, _earType;
int _legs;
bool _bark;

};

class breed : public dog


{
public:
breed( string color, string size)
{
_color = color;
setDogSize(size);
}

string getColor()
{
return _color;
}

// virtual function redefined


void setEars(string length, string
type)
{
_earLength = length;
_earType = type;
}

protected:
string _color, _earLength, _earType;
};

int main()
{
dog mongrel;
breed labrador("yellow", "large");
mongrel.setEars("pointy");
labrador.setEars("long", "floppy");
cout << "Cody is a " <<
labrador.getColor() << " labrador" <<
endl;
}

catch The following //


exceptions_trycatchandthrowstatements2.
syntax shows a try
cpp
block and its // compile with: /EHsc
handlers
#include <iostream>
using namespace std;
void MyFunc( void );

class CTest {
public:
CTest() {};
~CTest() {};
const char *ShowReason() const {
return "Exception in CTest
class.";
}
};

class CDtorDemo {
public:
CDtorDemo();
~CDtorDemo();
};

CDtorDemo::CDtorDemo() {
cout << "Constructing CDtorDemo.\n";
}

CDtorDemo::~CDtorDemo() {
cout << "Destructing CDtorDemo.\n";
}

void MyFunc() {
CDtorDemo D;
cout<< "In MyFunc(). Throwing CTest
exception.\n";
throw CTest();
}

int main() {
cout << "In main.\n";
try {
cout << "In try block, calling
MyFunc().\n";
MyFunc();
}
catch( CTest E ) {
cout << "In catch handler.\n";
cout << "Caught CTest exception
type: ";
cout << E.ShowReason() << "\n";
}
catch( char *str ) {
cout << "Caught some other
exception: " << str << "\n";
}
cout << "Back in main. Execution
resumes here.\n";
}
bool This keyword is a // bool.cpp
#include <stdio.h>
built-in type. A
variable of this int main()
type can have {
values true and #if !defined(__BOOL_DEFINED)
false. Conditional printf_s("bool is not
supported\n");
expressions have #elif defined(__BOOL_DEFINED)
the type bool and printf_s("bool is supported\n");
so have values of #endif
type bool. }
while Executes statement // while_statement.cpp
repeatedly until
#include <string.h>
expression evaluates #include <stdio.h>
to zero. char *trim( char *szSource )
{
The test of char *pszEOS = 0;
expression takes // Set pointer to character
place before each before terminating NULL
execution of the pszEOS = szSource +
loop; therefore, a strlen( szSource ) - 1;
while loop executes
// iterate backwards until non
zero or more times. '_' is found
expression must be while( (pszEOS >= szSource) &&
of an integral type, a (*pszEOS == '_') )
pointer type, or a *pszEOS-- = '\0';
class type with an return szSource;
unambiguous }
conversion to an int main()
integral or pointer {
type. char szbuf[] = "12345_____";

printf_s("\nBefore trim: %s",


szbuf);
printf_s("\nAfter trim: %s\n",
trim(szbuf));
}

volatile the volatile keyword // volatile.cpp


// compile with: /EHsc /O2
is a type qualifier
#include <iostream>
used to declare that #include <windows.h>
an object can be using namespace std;
modified in the
program by volatile bool Sentinel = true;
int CriticalData = 0;
something such as
the operating unsigned ThreadFunc1( void*
system, the pArguments ) {
hardware, or a while (Sentinel)
concurrently Sleep(0); // volatile spin
lock
executing thread.
// CriticalData load guaranteed
after every load of Sentinel
cout << "Critical Data = " <<
CriticalData << endl;
return 0;
}

unsigned ThreadFunc2( void*


pArguments ) {
Sleep(2000);
CriticalData++; // guaranteed to
occur before write to Sentinel
Sentinel = false; // exit critical
section
return 0;
}

int main() {
HANDLE hThread1, hThread2;
DWORD retCode;

hThread1 = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)&ThreadFunc1,
NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)&ThreadFunc2,
NULL, 0, NULL);

if (hThread1 == NULL || hThread2


== NULL) {
cout << "CreateThread failed."
<< endl;
return 1;
}

retCode =
WaitForSingleObject(hThread1,3000);

CloseHandle(hThread1);
CloseHandle(hThread2);

if (retCode == WAIT_OBJECT_0 &&


CriticalData == 1 )
cout << "Success" << endl;
else
cout << "Failure" << endl;
}

void When used as a // void.cpp


void vobject; // C2182
function return type, void *pv; // okay
the void keyword int *pint; int i;
specifies that the int main() {
function does not pv = &i;
return a value. When // Cast optional in C required in
C++
used for a function's pint = (int *)pv;
parameter list, void }
specifies that the
function takes no
parameters. When
used in the
declaration of a
pointer, void
specifies that the
pointer is
"universal."
Fundamental types
in C++ are divided
into three categories:
integral, floating,
and void. Integral
types are capable of
handling whole
numbers. Floating
types are capable of
specifying values
that may have
fractional parts.

The void type


describes an empty
set of values. No
variable of type void
can be specified —
it is used primarily
to declare functions
that return no values
or to declare generic
pointers to untyped
or arbitrarily typed
data. Any expression
can be explicitly
converted or cast to
type void. However,
such expressions are
restricted to the
following uses:

Anda mungkin juga menyukai