Você está na página 1de 18

C++Table of Contents

User-mode Linux ......................................................................................................................................1


Access Specifiers:......................................................................................................................................1
Mutable......................................................................................................................................................2
Friend functions.........................................................................................................................................2
Multiple inheritance...................................................................................................................................2
Pae 22!" #irtual Methods - P$L%morphism...........................................................................................2
Pae 1!1" Anon&mous 'lasses...................................................................................................................(
abstract class ) pure-*irtual functions.........................................................................................................(
pae 1(+ , static classes. Static in c- is much different than in c" almost opposite. ................................!
'.. /terators 0'alled enumerators in '-1:................................................................................................!
cout and cin:...............................................................................................................................................2
endl adds a 3e4line and flushes the buffer" clears it:................................................................................2
Usin a *ector instead of an arra&:.............................................................................................................5
'.. list container:......................................................................................................................................6
7e8ue container 0doubl& lin9ed 8ueue1.....................................................................................................6
#ectors........................................................................................................................................................6
:eadin all characters from a file............................................................................................................1;
<lements of the iostream librar& 0char instantitation1..............................................................................11
Function templates...................................................................................................................................12
Simple class templates.............................................................................................................................12
S3MP.......................................................................................................................................................1(
'.. inter*ie4 =uestions:........................................................................................................................1(
'.. Lanuae-specific Ans4ers........................................................................................................1!
b& 'urtis >raus9opf.........................................................................................................1!
Acron&ms............................................................................................................................................1?
User-mode Linux
0UML1 enables multiple *irtual Linux s&stems 09no4n as uests1 to run as an application 4ithin a
normal Linux s&stem 09no4n as the host1. As each uest is @ust a normal application runnin as a
process in user space"
Access Specifiers:
private members of a class are accessible onl& from 4ithin other members of the same class
or from their friends.
protected members are accessible from members of their same class and from their friends"
but also from members of their deri*ed classes.
public members are accessible from an&4here 4here the ob@ect is *isible.
Mutable
A const function promises not to modif& an& *ariables in the callin ob@ect. Aut it 'A3 modif& a
*ariable thatBs declared as mutable.
Friend functions
/n principle" pri*ate and protected members of a class cannot be accessed from outside the same class
in 4hich the& are declared. Co4e*er" this rule does not affect friends.
/f &ou 4ant
Multiple inheritance
/n '.. it is perfectl& possible that a class inherits members from more than one class. Dhis is done
b& simpl& separatin the different base classes 4ith commas in the deri*ed class declaration. For
example" if 4e had a specific class to print on screen 0COutput1 and 4e 4anted our classes
CRectangle and CTriangle to also inherit its members in addition to those of CPolygon 4e could
4rite:
1
2
class CRectangle: public CPolygon, public COutput;
class CTriangle: public CPolygon, public COutput;
Page 224, Virtual Methods P!"#$orphis$
Pol&morphism" 4hich means Eman& formsF" is achie*ed usin *irtual methods. See example on pae
22?.
11 Pol&morphism is the abilit& of a pointer to a deri*ed ob@ect to be t&pe-
compatible 4ith a pointer to its base class. /f the inter*ie4erBs follo4-up 8uestion
is" GCuhHG" &ou can ans4er:
Pol&morphism allo4s t4o or more classes deri*ed from the same base class to
share a common base member function but ha*e different beha*iors. Mo*in to a
4hiteboard" &ou can 4hip up the sample proram in Listin A. /t uses a pure
*irtual base member but thatBs not a re8uirement. A reular *irtual base member
4ould also ha*e been acceptable.
virtual void eat() const { std::cout << "I eat like a generic Animal." <<
std::endl; }
A method that is intended to be overridden is a virtual method. Sa& &ou ha*e a class that
implements a method called DoStrin01 based on itBs o4n properties" and then &ou inherit from this
class in a ne4 class that has different properties. Dhe Dostrin method in the ne4 class 4ill ha*e to be
o*erridden to 4or9 correctl& 4ith itBs o4n properties. Dhe name of the method sta&s the same" but for
each of the classes the& are implemented different.
Do override a virtual method, &ou need to use the 9e&4ord Eo*errideF:
public o*erride strin DoStrin01
I
base.DoStrin01J )) %ou could use the base 9e&4ord to execute the base classB method
...
K
Page %4%, Anon&$ous Classes
An Anon&mous class is a class that doesnJt ha*e a name.
Partial class
abstract class ' pure(irtual functions
An Abstract class is simpl& a class that can not be instantiated because it contains one or more pure-
*irtual methods 4hich ha*e no state that re8uires instansiation.
3o such thin as an GinterfaceG in '.." Dhis is a @a*a term. An abstract class is a class that you
cannot create an instance of because it has 1 or more pure-virtual methods. Pure-Abstract classes
are '..Bs e8ui* to an interface.
A pure-virtual method is a function that points to 3ULL.
class Abstract {
public:
virtual void pure_virtual() !;
};
%ou use an abstract class as a parent class to an& child class 4here &ou do 4ant to o*erride
function)method beha*ior.
Why Interfaces and Abstract classes work well together.
Let's says you have two classes that inherit the same interface. Now you have to implement the interface methods in
both classes. B!" Let's say the two classes that inherit the interface re#uire the $A%& %&!'() implementation for
the interface method. In other words" you'll need to have duplicate code because you'll need to implement the same
method in each class.
The best )a& to sol(e this is to create a *+, class and i$ple$ent the $ethod !*C+ in that ne) class, then
inherit the ne) class in both of the other classes that need that $ethod- !his is good* But" this new class only
contains a method and is not really is not a +(%,L&!& class -it.s $ore of an abstraction of t)o classes." so we
dont want to allow anyone to instantiate the class. !hus" we declare it an Abstract class so it can not be instantiated
with the /new0 keyword.
page %/0 1 static classes- Static in c2 is $uch different than in c, al$ost
opposite-
/nstance data in a class means that the data i.e. *ariable or method is rele*ant $3L% in that
instance of the class. Aut if &ou declare a static *ariable in a class" it ma9es the data stored in *ariable
act li9e itJs public to all instances of that class.
/f &ou declare a static class" it can onl& contain static methods and *ariables" 3$D /nstance
methods or *ariables. A static class should be used onl& to house static methods that 4ill be called from
other classes. Dhere is 3$ reason to e*er create an instance of a static class usin the Ene4F 9e&4ord"
because it doesnJt contain an& instance specific data an&ho4.
C++ 3terators 4Called enu$erators in C25:
ContainerType C; // Any standard container type, like std::list<sometype

for !ContainerType::iterator it " C#$egin!%; it &" C#end!%; ''it% (
std::cout << )it << std::endl;
*
ContainerType<+temType C; // Any standard container type o, +temType elements
-oid Process+tem! const +temType. + % // /unction 01ic1 0ill process eac1 item o,
t1e collection
(
std::cout << + << std::endl;
*

std::for_each! C#$egin!%, C#end!%, Process+tem %; // A ,or2eac1 iteration loop
forward iterators" bidirectional iterators" and random access iterators.
/terators are usuall& used in pairs" 4here one is used for the actual iteration and the second ser*es to
mar9 the end of the collection. Dhe iterators are created b& the correspondin container class usin
standard methods such as $egin!% and end!%. Dhe iterator returned b& $egin!% points to the first
element" 4hile the iterator returned b& end!% is a special *alue that does not reference an& element.
Lhen an iterator is ad*anced be&ond the last element it is b& definition e8ual to the special end iterator
*alue. Dhe follo4in example sho4s a t&pical use of an iterator.
cout and cin:
// i/o example
#include <iostream>
using namespace std;
int main !%
(
int i;
cout << "Please enter an integer value: ";
cin i;
cout << "The value you entered is " << i;
cout << " and its double is " << i)2 << ".\n";
return 3;
*
endl adds a *e)line and flushes the buffer, clears it:
// my first string
#include <iostream>
#include <string>
using namespace std;
int main !%
(
string mystring;
mystring " "This is the initial string content";
cout << mystring << endl; // my4tring $u,,er is cleared
mystring " "This is a different string content";
cout << mystring << endl;
return 3;
*
6sing a (ector instead of an arra&:
A vector is used in C++ because includes attributes such as begin, end, size etc...
http://www.cplusplus.com/reference/stl/vector/rbegin/
#include <iostream
#include <vector
using namespace std1
//declare arra!
std22vector3char4 tmparray-56" .7..1
//print size and contents outside function
cout 33 89n int $ain459n Si:e: 8 33 tmparray.si7e-. 33 8 b&tes-9n 81
for -int i861 i3tmparray.si7e-.1 i99.
cout 33 tmparray:i;1 cout 33 endl1
The :: Scope operator:
Cere is the complete example of class ':ectanle:
1
2
5
6
7
8
9
:
;
13
11
12
15
16
17
18
19
1:
1;
23
21
22
// classes example
#include <iostream>
using namespace std;
class CRectangle (
int <, y;
public:
void set=-alues !int,int%;
int area !% (return !<)y%;*
*;
// T1e :: means t1at set=-alues is not a glo$al ,unction
// $ut rat1er $elongs to t1e CRectangle class
void CRectangle::set_values !int a, int $% (
< " a;
y " $;
*
int main !% (
CRectangle rect;
rect#set=-alues !5,6%;
cout << "area: " << rect#area!%;
return 3;
*
area: 12
The most important ne thin! in this code is the operator of scope "::, to colons# included in the
definition of set=-alues!%. /t is used to define a member of a class from outside the class definition
itself.
%ou ma& notice that the definition of the member function area!% has been included directl& 4ithin
the definition of the CRectangle class i*en its extreme simplicit&" 4hereas set=-alues!% has onl& its
protot&pe declared 4ithin the class" but its definition is outside it. /n this outside declaration" 4e must
use the operator of scope 0::1 to specif& that 4e are definin a function that is a member of the class
CRectangle and not a reular lobal function.
The scope operator "::# specifies the class to hich the member bein! declared belon!s, rantin
exactl& the same scope properties as if this function definition 4as directl& included 4ithin the class
definition. For example" in the function set=-alues!% of the pre*ious code" 4e ha*e been able to use
the *ariables < and y" 4hich are pri*ate members of class CRectangle" 4hich means the& are onl&
accessible from other members of their class.
Dhe onl& difference bet4een definin a class member function completel& 4ithin its class or to include
onl& the protot&pe and later its definition" is that in the first case the function 4ill automaticall& be
considered an inline member function b& the compiler" 4hile in the second it 4ill be a normal 0not-
inline1 class member function" 4hich in fact supposes no difference in beha*ior.
$ointers to classes
/t is perfectl& *alid to create pointers that point to classes. Le simpl& ha*e to consider that once
declared" a class becomes a *alid t&pe" so 4e can use the class name as the t&pe for the pointer. For
example:
CRectangle ) prect;
prect is a pointer to ':ectanle...
expression can be read as
Mx pointed b& x
Nx address of x
x.& member & of ob@ect x
x-O& member & of ob@ect pointed b& x
0Mx1.& member & of ob@ect pointed b& x 0e8ui*alent to the pre*ious one1
xP;Q first ob@ect pointed b& x
xP1Q second ob@ect pointed b& x
xPnQ 0n.11th ob@ect pointed b& x
%onstructors and &estructors:
// example on constructors and destructors
#include <iostream>
using namespace std;
class CRectangle (
int )0idt1, )1eig1t;
public:
CRectangle (int,int!
"CRectangle (!
int area !% (return !)0idt1 ) )1eig1t%;*
*;
CRectangle::CRectangle !int a, int $% (
0idt1 " new int;
1eig1t " new int;
)0idt1 " a;
)1eig1t " $;
*
CRectangle::"CRectangle !% (
delete 0idt1;
delete 1eig1t;
*
int main !% (
CRectangle rect !5,6%, rect$ !7,8%;
cout << "rect area: " << rect#area!% << endl;
cout << "rectb area: " << rect$#area!% << endl;
return 3;
*
The 'eyord this
Dhe 9e&4ord t1is represents a pointer to the ob@ect 4hose member function is bein executed. /t is a
pointer to the ob@ect itself.
$ne of its uses can be to chec9 if a parameter passed to a member function is the ob@ect itself.
int '7umm&::isitme 0'7umm&N param1 I
if 0Nparam RR this1
return trueJ
else
return falseJ K
C++ list container:
'ompared to other base standard se8uence containers 0*ectors and de8ues1" lists perform enerall&
better in insertin" extractin and mo*in elements in an& position 4ithin the container" and therefore
also in alorithms that ma9e intensi*e use of these" li9e sortin alorithms.
The main drabac' of lists compared to these other se(uence containers is that they lac' direct
access to the elements by their positionJ For example" to access the sixth element in a list one has to
iterate from a 9no4n position 0li9e the beinnin or the end1 to that position" 4hich ta9es linear time in
the distance bet4een these. Dhe& also consume some extra memor& to 9eep the lin9in information
associated to each element 04hich ma& be an important factor for lare lists of small-siSed elements1.
;e<ue container 4doubl& lin=ed <ueue5
7e8ue se8uences ha*e the follo4in properties:
/ndi*idual elements can be accessed b& their position index.
/teration o*er the elements can be performed in an& order.
<lements can be efficientl& added and remo*ed from an& of its ends 0either the beinnin or the
end of the se8uence1.
Dherefore the& pro*ide a similar functionalit& as the one pro*ided b& *ectors" but 4ith efficient
insertion and deletion of elements also at the beinnin of the se8uence and not onl& at its end. $n the
dra4bac9 side" unli9e *ectors" de8ues are not uaranteed to ha*e all its elements in contiuous storae
locations" eliminatin thus the possibilit& of safe access throuh pointer arithmetics.
Vectors
#ectors are a 9ind of se8uence containers. As such" their elements are ordered follo4in a strict linear
se8uence.
#ector containers are implemented as d&namic arra&sJ Tust as reular arra&s" *ector containers ha*e
their elements stored in contiuous storae locations" 4hich means that their elements can be accessed
not onl& usin iterators but also usin offsets on reular pointers to elements.
Aut unli9e reular arra&s" storae in *ectors is handled automaticall&" allo4in it to be expanded and
contracted as needed.
#ectors are ood at:
Accessin indi*idual elements b& their position index 0constant time1.
/teratin o*er the elements in an& order 0linear time1.
Add and remo*e elements from its end 0constant amortiSed time1.
'ompared to arra&s" the& pro*ide almost the same performance for these tas9s" plus the& ha*e the
abilit& to be easil& resiSed. Althouh" the& usuall& consume more memor& than arra&s 4hen their
capacit& is handled automaticall& 0this is in order to accomodate for extra storae space for future
ro4th1.
'ompared to the other base standard se8uence containers 0de8ues and lists1" *ectors are enerall& the
most efficient in time for accessin! elements and to add or remove elements from the end of the
se(uence. )or operations that involve insertin! or removin! elements at positions other than the
end, they perform orse than de8ues and lists, and ha*e less consistent iterators and references
than lists.
>eading all characters fro$ a file
Dhis example prompts for the name of an existin text file and prints its content on the screen.
1
2
5
6
7
8
9
:
;
13
11
12
15
16
17
18
19
1:
1;
23
21
22
25
26
27
// istream get
>include <iostream
>include <fstrea#
using namespace std;
int main !% (
char c, str?278@;
i,stream is;
cout << ABnter t1e name o, an e<isting te<t ,ile: A;
cin#get !str,278%;
is#open !str%; // open file
while !is#good!%% // loop while extraction from file is possible
(
c " is#get!%; // get character from file
if !is#good!%%
cout << c;
*
is#close!%; // close file
return 3;
*
+le$ents of the iostrea$ librar& 4char instantitation5
http:))444.cplusplus.com)reference)iostream)iostream)
%lasses:
ios*base Aase class 4ith t&pe-independent members for the standard stream classes 0class1
ios Aase class 4ith t&pe-dependent members for the standard stream classes 0class1
istream /nput stream 0class1
ostream $utput Stream 0class1
iostream /nput)$utput Stream 0class1
ifstream /nput file stream class 0class1
ofstream $utput file stream 0class1
fstream /nput)output file stream class 0class1
istrin!stream /nput strin stream class 0class1
ostrin!stream $utput strin stream class 0class1
strin!stream /nput)output strin stream class 0class1
streambuf Aase buffer class for streams 0class1
filebuf File stream buffer 0class1
strin!buf Strin stream buffer 0class1
Function te$plates
Dhe preprocessor decides the t&pes at compile time.
A function template beha*es li9e a function that can accept aruments of man& different t&pes. /n other
4ords" a function template represents a famil& of functions. For example" the '.. Standard Librar&
contains the function template ma<!<, y% 4hich returns either x or y" 4hiche*er is larer. ma<!%
could be defined li9e this" usin the follo4in template:
"include <iostream#

template <t$pename %#
const %& ma'(const %& '( const %& $)
{
i)($ < ')
return ';
return $;
}

int main()
{
** %+is ,ill call ma' <int# (b$ argument deduction)
std::cout << ma'(-( .) << std::endl;
** %+is ,ill call ma'<double# (b$ argument deduction)
std::cout << ma'(-.!( ..!) << std::endl;
** %+is t$pe is ambiguous; e'plicitl$ instantiate ma'<double#
std::cout << ma'<double#(-( ..!) << std::endl;
return !;
}
http:))en.4i9ipedia.or)4i9i)DemplateU0prorammin1
Si$ple class te$plates
A function template pro*ides a specification for eneratin template functions" based on some
parameters" 4hich all share the same name and are treated as a unit 0meanin that" for instance" the
prorammer @ust calls ma< 4ith some aruments" and the appropriate instance of the template
materialiSes1.
Similarl&" a class template provides a specification for !eneratin! classes based on parameters. Dhe
follo4in section sho4s an ad*anced use of class templates to perform compile-t&pe computation on
t&pes. A more common use for class templates" is the definition of pol&morphic classes" such as
containers.
For example" the '.. standard librar& has a list container called list, hich is a template. Dhe
statement list$int% desi!nates or instantiates a lin'ed-list of type int. Dhe statement
list$string% desi!nates or instantiates a lin'ed-list of type string. Dhe template has some
additional parameters" 4hich ta9e default *alues if the& are not specified. For example" the prorammer
can 4rite a custom class that pro*ides memor& allocation ser*ices" and that class can be specified as an
arument to the list template" to instantiate a list container that is tihtl& coupled to this custom
allocator 0at compile time1.
A class template usuall& defines a set of eneric functions that operate on the t&pe specified for each
instance of the class 0i.e." the parameter bet4een the anle brac9ets" as sho4n abo*e1. Dhe compiler
4ill enerate the appropriate function code at compile-time for the parameter t&pe that appears bet4een
the brac9ets.
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
S+,$
-emember that . desi!ned all mibs for the v/0'. . as the only S+,$ contact for the
hole pro1ect. Also, all subsystems in v/0' retrieved and set data in the system via the
snmp a!ent that used an internal S+,$ client application.
Textual-%onvention-
2ua!e3/ 4 non-ne!ative numbers, ran!e: 5 4 6/76789/70
%ounter3/ 4 non-ne!ative numbers, ran!e: 5 4 6/76789/70
%ounter86 "v/# 4 ran!e 5 4 1:668966593957001810
timetic's 4 non ne!ative, ran!e: ran!e: 5 4 6/76789/70, units of hundreths of a second beteen events
octet strin! 4 ei!ht bit bytes. Textual conventions are declared usin! this base type.
;xample: a display-strin! is an octet strin! here each byte must contain an ascii
character.
lin'&on T-A$-T<$;
BCTBRPR+4B snmp
DAR+AEFB4 ( i,+nde< *
GB4CR+PT+OC
AA linkGo0n trap signi,ies t1at t1e sending
protocol entity recogniHes a ,ailure in one o,
t1e communication links represented in t1e
agentIs con,iguration#A
::" 2
C++ inter(ie) ?uestions:
C++ Language-specific Answers
http:))444.decompile.com)inter*ie4)'V2A
V2AU/nter*ie4UAns4ersUPaeU;!.htm
by %urtis =raus'opf
$ne strate& to use 4hen ans4erin a lanuae issue 8uestion is to examine the
8uestion from *arious perspecti*es. Some perspecti*es to consider are:
the lanuae author 4ants to pre*ent ambiuities
the '.. compiler *endor 4ant to simplif& the compilerBs implementation
the code 4riter 4ants clear rules for implementin a feature
the maintenance prorammer needs to understand existin code
leac& code should not be bro9en b& ne4 features
Dhe best ans4er is one that ac9no4ledes the tradeoffs that 4ere made to
accommodate one or more of the abo*e roups. Lhen re*ie4in &our *ideo or
audio tape" i*e &ourself extra credit for each roup that &ou mention and their
tradeoffs.
=11 An arra& is instantiated 4ith the ne4PQ operator. /s it sufficient to delete the
arra& usin a delete operator or should a deletePQ operator be usedH Tustif& &our
ans4er.
A11 Dhe deletePQ operator should al4a&s be used. Dhis restriction applies for both
built-in t&pes 0char" int and others1 and for areate t&pes 0structs and classes1.
Dhis is re8uired b& the '.. lanuae definition 0the Annotated '.. :eference
Manual1.
=21 'an / drop the PQ 4hen deletin an arra& of some built-in t&pe 0char" int" etc1H
A21 3o. Marshall 'lineBs '.. FA= Lite contains a ood explanation at
parashift.com.
=(1 Lhat is an example of 4hen a destructor is 3$D called at the end of scopeH
A(1 A@arne StroustrupBs '.. St&le and Dechni8ue FA= pro*ides an excellent
explanation at att.com. Dhe short ans4er is that ob@ects that are created on the
heap are not automaticall& destro&ed at the end of the scope that created the
ob@ect.
/n addition to A@arne StroustrupBs ans4er" / 4ould also add that staticall& created
ob@ects are also not destro&ed at the end of the scope.
=!1 <xplain stac9 un4indin.
A!1 Stac9 un4indin occurs 4hen an exception is thro4n and control passes from
a tr& bloc9 to a handler. Automatic ob@ects are destro&ed in the re*erse order of
their construction. /f a destructor thro4s an exception durin the stac9 un4indin
process" terminate is called.
From the Aorland '.. Auilder help:
When an exception is thrown, the runtime library takes the thrown
object, gets the type of the object, and looks upward in the call stack
for a handler whose type matches the type of the thrown object. Once
a handler is found, the RTL unwinds the stack to the point of the
handler, and executes the handler. n the unwind process, the RTL
calls destructors for all local objects in the stack frames between
where the exception was thrown and where it is caught. f a destructor
causes an exception to be raised during stack unwinding and does not
handle it, terminate is called. !estructors are called by default, but
you can switch off the default by using the "xd compiler option.
$b@ects that are not allocated on the stac9" such as heap allocations" are not
automaticall& released. Dhis can cause memor& lea9s unless the prorammer ta9es
extra precautions to release the allocated memor& 4hen an exception is thro4n.
Dhere are *arious 4a&s to pre*ent heap-memor& lea9s caused b& stac9
un4indin. $ne 4a& is a user-defined arbae-collectionJ a second 4a& is to
specificall& deallocate those resources in the exception handler.
=21 Lhen / 4rite a deri*ed classBs destructor" do / need to explicitl& call the
destructor for m& base classH
A21 Marshall 'lineBs '.. FA= Lite ans4ers this 8uestion 4ith G3oG. A more
explicit explanation 4ith an example is at parashift.com.
=51 <xplain the difference bet4een a class and an ob@ect.
A51 A class is a blueprint for an ob@ect. /t defines ho4 the ob@ect 4ill be created"
4hat data is stored" ho4 the data can be manipulated and ho4 the ob@ect 4ill be
destro&ed. An ob@ect is an instantiation of a class. Dhere can be multiple ob@ects
instantiated from one class. <*er& ob@ect has one and onl& one class that it 4as
instantiated from.
=?1 <xplain the difference bet4een a struct and a class.
A?1 Dhe default members and base classes of a class are pri*ate. Dhe default
members and base classes of a struct are public.
$ther than the default protection" struct and class are e8ui*alent.
An un4ritten practice amonst '.. prorammers is to define a class for ob@ects
that ha*e fe4 or no public data members and to define a struct for ob@ects that
ha*e fe4 or no public methods.
=+1 Lhat is difference bet4een malloc01)free01 and ne4)deleteH
A+1 malloc01 and ne4 both allocate space from the heap. free01 and delete both
release pre*iousl& allocated heap space. free01 should onl& be used 4ith mallocBd
allocations and delete should onl& be used 4ith ne4 allocations. Dhere are t4o
*arieties of ne4: arra& allocation throuh a ne4PQ operator and sinle ob@ect
allocation throuh a ne4 operator. /tBs the prorammerBs responsibilit& to 9no4
and trac9 4hich allocation method 4as used in order to appl& the correct
deallocation: free01" delete or arra& delete 0operator deletePQ1.
/n Listin A" pol&morphism occurs 4ith the #ehicle parameter for the printFuel01
function. printFuel01 can accept either an instantiation of 'ar or an instantiation of
Druc9.
A follo4-up 8uestion miht as9 if a #ehicle ob@ect could be passed to the
printFuel01 function. Dhe ans4er is GnoG because #ehicle uses a pure-*irtual
function and classes 4ith pure-*irtual functions can not be instantiated.
21 *irtual is a '.. 9e&4ord that is used for *irtual methods and for *irtual base
classes.
(1 mutable is a storae-class specifier. /t allo4s const-member functions to
modif& the data member.
!1 explicit is used on constructors that ha*e one parameter. /t pre*ents automatic
t&pe con*ersion from chanin a candidate parameter into the t&pe used in the
constructor.
21 template metapro!rammin! is an idiom that uses templates to enerate
source code that calculates an ans4er at compile-time rather than at run-time.
Follo4-up 8uestions 4ould as9 about the 'uriousl& :ecurrin Demplate Pattern"
the Aarton-3ac9man tric9" static pol&morphism in template metaprorammin
and the benefits and dra4bac9s of template metaprorammin. See 4i9ipedia.or
for a ood explanation alon 4ith cross reference material.
51 public, private and protected are the access control specifiers in class and
struct desins. All three of the 9e&4ords are used to control the access to methods
and data in base classes and in deri*ed classes. Listin A sho4s an example of a
'ar class definin public access to a #ehicle class. Dhe #ehicle class defines
public access of the etFuel01 pure *irtual method.
?1 Dhe static 9e&4ord is used all o*er the place in the '.. lanuae. Lhen used
inside of a method or function" the static 9e&4ord preser*es the last *alue of a
*ariable bet4een method or function calls. /nside of a class definition" a data
*alue can be declared static -- this causes one *ersion of the data to be shared
amonst all of the ob@ects of the class. Static member functions can not be *irtual
because the& ha*e external lin9ae. <xternal lin9ae means that the function does
not ha*e a this pointer and the function can onl& call other static member
functions and access static data.
+1 An assi!nment operator is a simple e(ual "># si!n for built-in t&pes or the
operatorR01 method for ob@ects. /f &our first ans4er onl& pro*ided one of those
assinment operators" a ood inter*ie4er 4ould as9 somethin li9e Gis that allHG.
Lritten tests canBt do that" of course" so be careful 4hen i*in 4hat seems li9e
an ob*ious ans4er.
61 A dan!lin! pointer can be an unassined pointer or it can be a pointer to an
ob@ect that has been destro&ed.
1;1 A functor is short for function ob@ect. Function ob@ects are used as callbac9s
to modif& or customiSe the beha*ior of an alorithm. Function ob@ects define a
member function that pro*ides the lue bet4een an alorithm and the customiSed
beha*ior. Aecause functors are full-fleded ob@ects" the& ha*e all of the po4er of
an ob@ect: state" inheritance" encapsulation and templates. /n Listin A" the
operator01 method of the manitude structure is a functor. Listin ' ta9es a
slihtl& different approach b& usin an arbitrar& method name" in this case called
GisWreaterDhanG" to attach a customiSed beha*ior to an alorithm.
Acronyms
Tust li9e definitions" tr& to 9eep the ans4ers to acron&ms short.
11 STL: Standard Demplate Librar&
21 -A..: :esource Allocation is /nitialiSation. See http:))444.hac9craft.net)raii)
for a 4ell-4ritten tutorial on :A//.
(1 ?%L: #isual 'omponent Librar&. /Bll admit that e*en thouh / 9ne4 4hat the
#'L 4as" / didnBt 9no4 4hat its acron&m stood for until / 4rote this article.
!1 %@@: =uote from 'hapter 1 of the '.. Prorammin Lanuae 0Stroustrup1
#The name $%% ... was coined by Rick &ascitti in the summer of
'()*. The name signifies the e+olutionary nature of the changes from
$, #%%# is the $ increment operator.#
21 A A%har t&pe in a proram &ou didnBt 4rite 4ould t&picall& be a 4ide 015-bit1
character t&pe

Você também pode gostar