Thứ Hai, 10 tháng 2, 2014

Tài liệu Giáo trình C++ P6 ppt


www.gameinstitute.com Introduction to C and C++ : Week 6: Page 5 of 44
But what if we’re using two APIs, and both define a data type with the name “Player”? Now, not only are
we prohibited from using this name, but our code will not compile because there is a name conflict. In
this situation, there is no way to proceed without getting the maker of one of the other APIs to change the
name of their data types. As things stand, the two APIs are incompatible.

Before the introduction of namespace support, API developers would often prefix their data type names
with the name of the company, the name of the API, or an acronym, like this:

class abcPlayer // API “ABC” prefixes all of their data types with “abc”
{
};

struct defPlayer // API “DEF” does the same thing
{
};

This prevented the name conflict problem—most of the time. But there is still a chance that two different
companies will use the same name. And furthermore, the name of each data type is now obscured.

Namespaces allow data types to be declared in a private namespace, or scope. This prevents data type
names from cluttering the global namespace, and therefore prevents name conflicts. (As long as the name
of the namespace itself is unique.) Using namespaces, the APIs abc and def would define their own
version of “Player” without a prefix:

namespace abc
{
struct Player
{
};
};

namespace def
{
class Player
{
};
};

This code defines two different data types, both named Player, but each within its own namespace, so
there is no conflict. What’s more, since the Player name is kept out of the global namespace, we’re free
to use the name “Player” in our code:

namespace abc
{
struct Player
{
};
};

namespace def
{
class Player
{
};

www.gameinstitute.com Introduction to C and C++ : Week 6: Page 6 of 44
};

typedef int Player;

Each usage of the name “Player” refers to a different data type. One is a class, one is a structure, and one
is a typedef to an int. But, because each resides in a separate namespace, there is no conflict (the typedef
version of Player exists in the global namespace).

What’s the catch? Each time you use the name “Player”, you must specific which one you’re referring to.
By default, the global namespace is used, so in this case you’ll get the global “Player”, like this:

Player p; // p is an ‘int’ (via typedef)

If the global Player typedef shown above were not defined, then using the plain name “Player” would
fail, because no such data type exists not in the global namespace.

To indicate a data type that is part of a non-global namespace, the scope resolution operator (::) must be
used, like this:

abc::Player p1;
def::Player p2;

These declarations create two different variables, each with a different type, despite the fact that the data
type name is “Player” in both cases. The first creates a variable based on Player as defined within the abc
namespace, while the second uses the Player data type from the def namespace. We can prove that the
two variables are different by adding member functions to each version of Player:

namespace abc
{
struct Player
{
void Blah();
};
};

namespace def
{
class Player
{
public:
void Yak();
};
};

abc::Player p1;
def::Player p2;

p1.Blah();
p2.Yak();

These function calls are specific to each version of Player, so the fact that this code compiles proves that
the p1 and p2 variables are indeed based on different types.


www.gameinstitute.com Introduction to C and C++ : Week 6: Page 7 of 44
Any number of different data types can be added to a namespace. Here, a namespace called xyz is defined
that includes typedefs, a structure, and a function:

namespace xyz
{
typedef int Type1;
typedef float Type2;
struct Type3
{
};
void Func()
{
}
};

Using data types that are defined as part of a namespace can be performed either with the scope resolution
operator for each usage, like this:

xyz::Type1 a;
xyz::Type2 b;
xyz::Type3 c;
xyz::Func();

Or with the using keyword, which activates a namespace for use by the code that follows:

using namespace xyz;

Type1 a;
Type2 b;
Type3 c;
Func();

The using keyword activates a namespace, but it does not prohibit the usage of names in the global
namespaces, so the code above has access to both the xyz and the global namespace. As a result, the
using keyword doesn’t work with names that are present in both namespaces::

namespace xyz
{
typedef int Type1;
typedef float Type2;
struct Type3
{
};
void Func()
{
}
};

void Func();

using namespace xyz;

Func(); // compiler error! The name “Func” is ambigous


www.gameinstitute.com Introduction to C and C++ : Week 6: Page 8 of 44
This code won’t compile, despite the fact that the xyz namespace has been activated with the using
keyword. In this case it is necessary to use the scope resolution operator to indicate which version of
Func we’re referring to:

xyz::Func(); // calls Func as provided in the xyz namespace

::Func(); // calls the global version of Func

Using the scope resolution operator with no preceding scope indicates the global namespace. This is only
necessary if the current scope includes a name that is the same as one in the global namespace.

During the normal course of game programming, it is not normally necessary to define new namespaces.
Even on a large project, name conflicts are fairly unlikely, but if it does crop up, it is usually just a matter
of talking with the programmer in the next cubicle to decide which type can be renamed to resolve the
conflict.

Using existing namespaces is more common, as many APIs define their data types within non-global
namespaces to avoid conflict. This includes APIs that are part of the standards libraries, as we’ll soon see
when we look at STL.
Templates
Another feature added to C++ after it had become widely used is templates. A template is an incomplete
type. One or more key elements are missing, but can be provided when the data type is used. Templates
are sometimes called parameterized types because they take parameters. But unlike a function, template
parameters are data types—not data values. Consider this code:

template <class T> class Data
{
public:
T GetValue() { return value; }
void SetValue (T v) { value = v; }
private:
T value;
};

This is a template for a class called Data. This template takes one parameter called T (a capital T is the
standard name for a template parameter.) The definition begins with the template keyword, and is
followed by a template parameter list. In this case there is only one parameter, but there can be any
number of parameters. Unlike function parameter lists, template parameter lists are enclosed in angle
brackets. Most of the time parameter names are preceded by the class keyword, but class has a different
meaning when used in this context. A template parameter that uses the class keyword can be any data
type, not just a class.

The Data class declares two member functions and a data member. The functions allow the private data
member to be assigned, and retrieved. Notice the type used as a return value for GetValue, the argument
for SetValue, and the data member. Instead of a type like int, or float, the template parameter name is
used. In each case the data type used is contingent on the parameter passed to the template as T.

In order to use a template, a data type must be supplied, like this:

Data<int> dataObject1;
Data<float> dataObject2;

www.gameinstitute.com Introduction to C and C++ : Week 6: Page 9 of 44

In this case dataObject1 is an instance of the Data class that is parameterized on the int type. The result
is that this object can be used as though each instance of T were actually an int. Likewise, dataObject2
uses the float type. These objects can then be used like this:

dataObject1.SetValue( 33 );
int val1 = dataObject1.GetValue();
cout << val1 << endl; // displays 33

dataObject2.SetValue( 44.5f );
float val2 = dataObject.GetValue();
cout << val2 << endl; // displays 44.5

Once an object has been created based on a template class, there’s no evidence that it is template-based. It
can be used as if the class upon which it is based were written specifically with the provided data type.

Any data type can be used as a template argument, including pointers:

Data<Player*> obj;
Player p;

Obj.SetValue( &p );
Obj.GetValue()->SetName( “slowpoke” );

What are templates for? Templates allow the definition of generic data types. They can be used to write
classes that aren’t specific to any single data type. Templates are often used to write container classes, as
we’ll see in the next section.
STL
As its name implies, the Standard Template Library (STL), is a set of templates. Now part of the standard
C++ libraries, these templates provide functionality that is extremely flexible and powerful.

STL provides support for several data containers. Because they are templates, these containers are
completely generic. They can be used to store any type of data. We won’t cover all of the STL templates,
but STL defines these containers:

• string
• list
• deque
• stack
• vector
• map
• set

Although we won’t cover all of these types, most of the STL containers work in a similar way. The string
data type is a container that stores characters. Unlike other types, string doesn’t require a template
argument, because it is actually a typedef for the STL basic_string type, which is templatized on the
char type, like this:

typedef basic_string<char> string;


www.gameinstitute.com Introduction to C and C++ : Week 6: Page 10 of 44
All of the STL data types are defined in std namespace (short for standard), so this namespace must be
specified with the scope resolution operator, or the using keyword. Declaring a string, therefore looks like
this:

std::string str1;

// or

using namespace std;
string str2;

The string type, through basic_string, provides a host of copy constructors, overloaded operators, and
member functions, all of which serve to make string handling much easier than it is with char arrays.
Here’s an example:

using namespace std;

string a("one"); // string ‘a’ contains “one”
a.append(" "); // append one space to the end
a+="two"; // append another string (‘+=’ is the same as append)
string b(" three"); // string ‘b’ contains “three”
a+=b; // append an object of the string type
int size = a.size(); // retrieve the string length

cout << a.data() << " size=" << size << endl;
// displays ‘one two three size=13’

(If this seems familiar, that is probably because we used the STL string class in Lesson 3 to implement
the HighScores sample.)

The overloaded constructors and operators that the string class provides are nice, but that’s just the
beginning of what this class can do. The string class also provides support for searching, replacing, and
inserting. Likewise, the other STL containers provide member functions that provide convenient features,
such as sorting.

Many of the STL container features rely on the concept of an iterator. An iterator is a class that is
designed solely for manipulating the contents of a container object. STL iterators provide a number of
overloaded operators that allow them to be used just like pointers.

STL defines a different iterator for each container, but the iterator class always has the name iterator.
This is possible because the iterator class is defined inside the container class. As a result, the scope
resolution operator must be used in order to access the iterator data type. For the string class, declaring
an iterator looks like this:

std::string::iterator it;

Despite the odd syntax, this is a simple object declaration. An iterator called it is declared based on the
iterator class, which is defined within the scope of the string class, which in turn is part of the std
namespace; hence the use of two scope resolution operators.

This new iterator is initialized, as the string::iterator class provides a default constructor, but the new
object doesn’t indicate an element until used with an existing instance of string, like this:

www.gameinstitute.com Introduction to C and C++ : Week 6: Page 11 of 44

std::string str(“bolt”);
std::string::iterator it( str.begin() );

This code creates a string called str, and uses the begin member function to return an iterator to the first
string element. In this case the element is the character ‘b’. Now the iterator can be used to retrieve and
assign the contents of the str string. STL overrides the de-reference operator for this purpose, making the
iterator appear as though it is a pointer:

cout << str.data() << endl; // displays ‘bolt’
cout << *it << endl; // displays ‘b’
*it = ‘c’; // assign ‘c’ o the element indicated by ‘it’
cout << *it << endl; // displays ‘c’
cout << str.data() << endl; // displays ‘colt’

To add to the illusion that an iterator is actually a pointer, the iterator class overrides the increment and
decrement operators, which can be used to traverse the elements in the container:

it++; // advances the iterator to the next element
cout << *it << endl; // displays ‘o’
it ; // retreat to previous element
cout << *it << endl; // displays ‘c’

These operators make iterating through a collection of data items stored in an STL container very easy:

std::string s("STL");

for (std::string::iterator it = s.begin(); it != s.end(); it++)
cout << " " << *it ;

In this case a for loop is used to declare an iterator to the first element of a string, and traverse the string
until the end is reached. The stop condition is implemented by comparing the iterator with the return
value from the end member function, which returns an iterator indicating the last element in the string.
This loop displays “ S T L”.

At the very least, STL is a boon for game programmers because they no longer have to write their own
versions of the various container classes that games often require. Before STL, one of the first steps in
programming a game was either writing custom container classes, or locating existing containers. In
either case this was a waste of time, as a properly designed container class is generic enough that it can be
written once and forgotten about.

The string class has obvious benefits, but what about the other STL containers? The list container is an
implementation of a doubly linked list. This type of data structure is similar to an array except that the
elements of the list are not stored contiguously in memory. Instead, each element is a node that is linked
to the next and previous nodes via pointers. There is a performance penalty for this layout, but the
advantages are that the list size is limited only by the amount of available memory. It is also much faster
to insert elements into the list because the new data can be linked into the list without moving the existing
elements.

Unlike the list class, the deque class is more like array. This gives it performance benefits for simple
traversals, but inserting elements into the container is expensive because the existing items must be
moved to make room for the new data. The deque class has an advantage over a basic array because

www.gameinstitute.com Introduction to C and C++ : Week 6: Page 12 of 44
adding items to the front of the collection does not require that the existing items be moved. In the next
section we’ll use this container to write a sample.

The stack container implements a data container in which items can only be added and removed from one
end of the collection. Stacks are sometimes used to implement menu systems in which a collection of
menus can be presented, one over the other. Only the topmost menu has focus, and when it is removed
from the top of the menu stack, the next menu gains the focus. The terms “push” and “pop” are typically
used to describe stack operations. We’ll use this technique for a menu system in the game presented later
in this lesson.

The term vector, used in the context of STL, refers to a container that behaves like a dynamic array not a
data structure that indicates direction and velocity. Unlike the deque container, items cannot be added to
the front of a vector, just as items can’t be added to the beginning of an array without moving all existing
items. The vector class overloads the square bracket so that elements can be accessed as though the
container is a C++ array.

The map container uses a key system to provide access to its contents. Each item added to a map is
accompanied by a key that is used by the map container to store the item. If the item is required later, it
can be located quickly by providing the key. Maps are useful for large collections of items that cannot be
indexed easily. For example, if a collection of objects must be identified by a large range of numbers,
allocating an array large enough to store an element for each possible index is out of the question. The
memory requirements would be excessive, and most of the array elements may be unused. A map can be
used to store data items whose indices are not actually indices into an array. Maps are therefore
sometimes called sparse arrays.

Finally, the set container stores a collection of items that don’t have any intrinsic order. Items can simply
be added to the collection. The concept of a set is prevalent in mathematics.

Notice that, through the use of namespaces, each of the STL container types uses an exceedingly simple
name. This would be very bad form if namespaces weren’t used because it would prohibit the global use
of simple names like list, set, and string.
The Snake Sample
Rather than using the string class to demonstrate STL in a boring console application, let’s use a DirectX
enabled application. We’ll use the deque class to store a list of two-dimensional points. A spherical
model will be drawn at each of these points, and each update cycle will remove a point from the end of
the deque and add one at the beginning. The result is the animation of a shape that looks something like a
snake. The final executable looks like this:


www.gameinstitute.com Introduction to C and C++ : Week 6: Page 13 of 44


To add a bit of interaction, we’ll configure the F2 key to prohibit the removal of deque elements from the
end of the collection, causing the length of the collection to be increased with each update cycle, and the
F3 key to prohibit the addition of new deque elements, causing the “snake” to shrink.

The first step is to add a few data member to the application class, which—naturally—is derived from the
D3DApplication class:

typedef std::deque<POINT> PointDeque;
PointDeque pointDeque;
int xInc, yInc;
bool grow, shrink;
D3DModel sphereModel;

Namespaces and templates are valuable and powerful features, but the syntax required to use them can be
awkward. For this reason, it’s often a good idea to use a typedef to create a simpler alternative name. In
this case we’ve defined the name PointDeque as an alias for the STL deque, parameterized on the
POINT structure. This new name is used immediately after it is defined, to create data members of this
container type.

The xInc and yInc integers will be used to indicate the amount by which each axis is incremented each
time a new point is added to the front of the deque. We’ll use the grow and shrink Booleans to track
whether the F2 and F3 keys are currently being pressed. The last data member is an instance of
D3DModel. As with the Circle sample, although we’ll be rendering multiple instances of the model, only
one model object is required.

www.gameinstitute.com Introduction to C and C++ : Week 6: Page 14 of 44

We’ll also use some literal constants to define values used in the implementation:

const int LimitX = 200;
const int LimitY = 150;
const int IncX = 7;
const int IncY = 4;
const int SnakeLenInitial = 50;
const int SnakeLenMax = 300;
const int SnakeLenMin = 2;
const char* SphereModelFile = "lowball.x";

The LimitX and LimitY values are used to keep the snake in the window. If the snake advances beyond
these values, either in the positive or negative direction, we’ll reverse the sign of the xInc or yInc data
member to reverse the direction in which the snake will advance. The IncX and IncY constants are used
as initial values for the xInc and yInc data members.

The next three values control the number of elements in the container, and therefore the length of the
snake. Initially we’ll add 50 points to the deque. If the user presses F2, we’ll stop the removal of points,
but only until the deque size reaches SnakeLenMax. Likewise, pressing F3 will stop new points from
being added to the deque, but only until the size reaches SnakeLenMin.

The SphereModelFile constant is a string containing the name of the .x file from which the spherical
model will be loaded. Notice that we’re using a different .x file for this sample. The Circle sample used a
model called sphere.x, but this model was fairly high-resolution—meaning that it was composed of
hundreds of polygons. For this sample, because we may be rendering as many as 300 instances of the
model, we’re using a much lower resolution model, with closer to a dozen polygons. In fact, the lowball.x
model is actually a hemisphere whose rounded side faces the camera. This will save us the processing
power of processing polygons that won’t appear because they’ll be hidden by the front of the model.
These types of optimizations are typical of 3D graphics programming. For performance reasons, every
effort must be made to reduce the number of polygons required while still maintaining an effective visual
effect.

Now that we have our data member and constants in place, we’re ready to initialize the application:

bool SnakeApp::AppBegin()
{
// initialize DirectInput
inputMgr = new eiInputManager( GetAppWindow() );
keyboard = new eiKeyboard();
keyboard->Attach( 0, 100 );

// initialize Direct3D
UseDepthBuffer( false );
HRESULT hr = InitializeDirect3D();
if (FAILED(hr))
{
return false;
}

// prepare the "snake"
int x = 0, y = 0;
for (int i=0; i<SnakeLenInitial; i++)

Không có nhận xét nào:

Đăng nhận xét