




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
ClassOperator
overloadingAutomatic
type
conversionInheritance
&
CompositionPolymorphism
&
Virtual
FunctionsThe
C
in
C++Object-Oriented
Programming3.1
ClassObjectObject=
EntityObject
=
Attributes
+
ServiceDataOperationsObject-Oriented
ProgrammingProblem
spaceSolution
spacemap?Object-Oriented
Programmingion:
From
the
problem
space
to
the
solution
one.?ion
data
type(
Class
)The
ability
to
package
data
with
functions
allows
you
to
create
a
newdata
type.
This
is
often
called
encapsulation.
This
newdata
type
iscalled
“
ion
data
type”.Object-Oriented
ProgrammingC++
Access
ControlC++
introduces
three
new
keywords
to
set
the
boundaries
in
a
structure:public,
private,
and
protected.public:
means
all
member
declarations
that
follow
are
available
toeveryone.
public
members
are
like
struct
members.private:
means
that
no
one
can
access
that
member
except
you,thecreator
of
the
type,
inside
function
members
of
that
type。is
a
brick
wall
between
you
and
the
client
programmer;
ifsomeonetries
to
access
a
private
member,
they’ll
get
a
compile-time
error.Object-Oriented
Programmingprotected:
acts
just
like
private,
with
one
exception
that
we
can’treally
talk
about
right
now:
“Inherited”
structures
(which
cannot
accessprivate
members)
are
granted
access
to
protected
members.Information
hidingInformation
hiding
is
a
design
strategy-Hide
details
that
may
change-Expose
interfaces
that
will
be
constant
(relatively)Object-Oriented
ProgrammingHow
to
define
a
classDeclarations
part(head
file)class
class-name
{private:
private
memberpublic:
public
member};Data
memberMember
functionObject-Oriented
Programmingunit
three\complex\simple
complex\Object-Oriented
ProgrammingImplementation
part(member
function
definition)[inline]
type
className::function_name(
parameter
list){function
body}Control
AccessMembers
see
all
membersObject-Oriented
ProgrammingClients
only
access
public
membersC++
access
controlObject-Oriented
ProgrammingCreate
Object(instance)Complex
c;
//
just
as
you
create
a
float
by
sayingfloat
f;Object VS
Class-Object (Complex
)Represent
things,
events,
or
conceptsRespond
to
messages
at
run-time-Class
(Complex
class)Define
properties
of
instancesAct
like
types
in
C++Using
classObject-Oriented
ProgrammingObject-Oriented
ProgrammingSend
messages
to
themcomplex
c;c.initialize(1.1,2.2);c.print();Message-Composed
by
the
sender-Interpreted
by
the
receiver-Implemented
by
methods-May
cause
receiver
to
change
state-May
return
resultsUsing
Objectcomplex
a(1.1,2.2);complex
*p
=
&a;Object-Oriented
Programmingp->print();a.print();//Make
the
call
using
the
object
pointer//
Make
the
call
using
the
object
nameObject
pointerHow
to
create
an
object(instance)?當(dāng)創(chuàng)建complex類的對象a時,以complex類定義為樣板建立a的相應(yīng)的數(shù)據(jù)成員,但它并不為對象a從complex類定義中拷貝所定義的操作代碼。也就是:
complex類定義中的成員函數(shù)代碼 在某塊公用的
空間中,供該類的所有對象共享---代碼共享。Complex
a,
b;Object-Oriented
ProgrammingObject-Oriented
ProgrammingThe
answer
is
“about
what
you
expect
from
a
C
struct.”The
size
of
a
object
is
the
combined
size
of
all
of
itsmembers.Youcan
determine
the
size
of
an
object
using
the
sizeof
operator.How
big
is
an
object(instance)?Initialization
&
Cleanupvoid
complex::initialize(double
rp,double
ip){real_part
=
rp;imaginary_part
=
ip;}complex
c;
//declaring
objectc.initialize(1.1,2.2);
//initializing
object,f
et??c.print();
//using
objectObject-Oriented
ProgrammingObject-Oriented
ProgrammingA
constructor
is
a
special
member
functionSame
name
as
its
classNo
return
typeInvoked
implicitly
when
instance
is
createdcan
be
overloadingConstructorsIn
C/C++,
the
data
that
storaged
in
stack
and
static
store
arereleased
by
systemHow
to
cleanup
an
objectint
i;
//global
objectstatic
int
k;
//static
global
objectint
fun(int
i){int
temp
=
i*2;//local
objectstatic
int
g;
//static
local
objectreturn
temp;}Object-Oriented
ProgrammingObject-Oriented
ProgrammingIn
C/C++:the
data
that
storaged
in
heap
are
released
byprogrammerint
main(){char*
p
=
(char*)malloc(200);…free(p);
//
released
by
programmerFile
fp
=
fopen(“myfile.txt”);…fclose(fp);
//released
by
programmer}Object-Oriented
Programmingvoid
main(){ complex
a(1.1,
2.2);complex
*p
=
(complex*)malloc(sizeof(complex));free(p);}a
and
p
itself
arereleased
by
systemAnonymity
complexin
heap
is
releasedbyprogrammerObject-Oriented
Programmingunit
three:student.dswObject-Oriented
ProgrammingHow
to
cleanup
an
objectStudent::~Student()
//destructor{if
(name
!=
NULL)free(name);}void
main(){Student
zhangsan("
",22,"男");}destructor
is
called
automatically
bythe
compiler
when
the
object
goes
out
ofscope.Object-Oriented
ProgrammingObject-Oriented
ProgrammingCalled
when
an
instance
is
deallocatedName
is
~ClassnameDoes
not
take
any
argumentsDoes
not
declare
a
return
typeCan’t
be
overloadingDestructorthis:
the
address
of
the
object
for
which
it
is
being
plex
a;分兩步:首先,編譯器為a分配sizeof(Complex)大小的空間,得到
this值(為a對象的起始地址),但此時this指向的是一片未初始化的空間。第二步,調(diào)用構(gòu)造函數(shù)Complex()來初始化this指向的區(qū)域,也就是對象a。this
pointerObject-Oriented
ProgrammingObject-Oriented
ProgrammingDeclarationObject
Lifetimeunit
three/object_scopeRequires
the
user
to
write
destructor
in
complex
class
?Default
constructor
and
defau
estructorclass
Student{private:char
name[20];short
age;char
sex[3];};requires to
writedestructor?Object-Oriented
ProgrammingWhen
designing
a
class,
as
a
rule,an
intact
interface
includes:constructor(several?)destructor(Need
to
do?)operetor=access
functions(set et
private
data
member)
etc.get方法可以控制返回給客戶的數(shù)據(jù)格式。set方法可以檢查對private變量值進(jìn)行修改的企圖,確保新值對那個數(shù)據(jù)成員來說是合適的、完整的、一致的。條款18:to
make
the
class
interface
is
complete
andminimal(Effective
C++)Object-Oriented
Programming它使程序從
工程的角度看顯得更具有
。set和get方法雖然提供了對private數(shù)據(jù)的 ,但通過控制這些
器的實現(xiàn),就能控制客戶代碼能對數(shù)據(jù)進(jìn)行什么操作。能在類的客戶面前隱藏數(shù)據(jù)成員的
表示方式。因此,如果數(shù)據(jù)的表示方式發(fā)生改變(通常是為了減少所需的
空間,或者為了改進(jìn)性能),那么只需修改方法的實現(xiàn),客戶端的實現(xiàn)則無需更改---只要方法提供的接口予以保留。Object-Oriented
ProgrammingObject-Oriented
ProgrammingThinking
in
C++5:
Hiding
the
Implementation6:Initialization
&
cleanupObject-Oriented
ProgrammingClassOperator
overloadingAutomatic
type
conversionInheritance
&
CompositionPolymorphism
&
Virtual
FunctionsThe
C
in
C++Object-Oriented
Programming一般說來,C++預(yù)定義類型(char、int、float等)的操作用運(yùn)算符來表示,其調(diào)用形式是表達(dá)式,中綴性式:a+b
,前綴形式:++a,后綴形式:a++。用戶定義的類型的操作則用函數(shù)表示,對它采用顯式調(diào)用。為了使用戶定義的類型與系統(tǒng)預(yù)定義類型相一致,也允許對用戶定義的類型使用運(yùn)算符來表示操作,如set1+set2,matrix1*matrix2。這種一致性還表現(xiàn)在可以為用戶定義的類型提供初始化、賦值以及轉(zhuǎn)換規(guī)則等。3.2
Operator
overloadingDefining
an
overloaded
operator
is
like
defining
a
function,
but
thename
of
that
function
isoperator@,
in
which
@represents
theoperator
that’s
bein erloaded.
The
numb of
arguments
in
theoverloaded
operator’s
argument
list
depends
on
two
factors:SyntaxObject-Oriented
ProgrammingObject-Oriented
ProgrammingWhether
it’s
a
unary
operator
(one
argument)
or
a
binaryoperator
(two
arguments).Whether
theoperator
isdefined
as
a
global
function
(oneargument
for
unary,
two
for
binary)
or
a
member
function(zero
arguments
for
unary,
one
for
binary
–
the
objectes
the
left-hand
argument).成員函數(shù)版_complex友員函數(shù)版_complexC++中的友員相當(dāng)于為封裝隱藏這堵不透明的墻開了一個小孔,任何該類的朋友可以通過這個小孔窺視該類的私有數(shù)據(jù)。注意友員函數(shù)與成員函數(shù)的區(qū)別:友員函數(shù)在類中
,但不是該類的成員函數(shù),不能通過this指針調(diào)用。friendObject-Oriented
Programming象程序設(shè)計風(fēng)格的性變差。在以下使用全局友員函數(shù)是不恰當(dāng)?shù)?。它破壞了面一致性,使?shù)據(jù)封裝性受到削弱,導(dǎo)致程序的可情況發(fā)生,考慮使 員函數(shù):-在類的設(shè)計中沒有為類定義完整的操作集,將友員函數(shù)作為對類的操作的一種補(bǔ)充形式。-考慮運(yùn)行效率。Friend-
函數(shù)
-
成員函數(shù)
-
類Object-Oriented
ProgrammingObject-Oriented
ProgrammingDeclare
non-member
functions
when
type
conversions
should
applyto
all
parameters.[若所有參數(shù)皆需類型轉(zhuǎn)換,請為此采用non-member函數(shù)重載]Member
function
VS
non-member
functionObject-Oriented
ProgrammingAlthough
you
can
overload
almost
all
the
operators
available
in
C,the
use
of
operator
overloading
is
fairly
restrictive.
In
particular,
youcannotcombine
operators
that
currentlyhave
nomeaning
in
C
(such
as
**
torepresent
exponentiation),
you
cannot
change
the
evaluationprecedence
ofoperators,
and
youcannot
change
the
number
ofarguments
required
by
an
operator.
This
makes
sense
–
all
of
theseactions
would
produce
operators
that
confuse
meaning
rather
than
clarifyit.Overloadable
operatorsThere
are
certain
operators
in
the
available
set
that
cannotbe
overloaded.
Teral
reason
for
the
restriction
is
safety.
Ifthese
operators
were
overloadable,
it
would
somehow
jeopardize
or
break
safety
mechanisms,
make
things
harder,
or
confuse
existing
practice.Operators
you
can’t
overload·
*
::
:?
sizeofObject-Oriented
ProgrammingObject-Oriented
ProgrammingUnary
Operatorsto
overload
all
the
unary
operators,
in
the
form
of
both
globalfunctions
(non-member
friend
functions)
and
as
member
functions.Binary
OperatorsC12:
Byte.cpp
成員函數(shù)版/Unary.cpp
友員版C12:Integer.h/Integer.cpp/IntegerTest.cpp友員版
Byte.h成員函數(shù)版Object-Oriented
ProgrammingIn
some
of
the
previous
examples,
the
operators
may
be
members
or
non-members.Which
should
I
choose?In
general,
if
it
doesn’t
make
any
difference,
they
should
bemembers,
to
emphasize
the
association
between
the
operator
and
itsclass.
When
the
left-hand
operand
is
always
an
object
of
the
current
class,this
works
fine.Basic
guidelinesObject-Oriented
ProgrammingHowever,
sometimes
you
want
the
left-hand
operand
to
be
an
object
ofsome
other
class.
A
common
place
you’ll
see
this
is
when
the
operators<<
and
>>
are
overloaded
for
iostreams.
Since
iostreams
is
a
fundamentalC++
library,
you’ll
probably
want
to
overload
these
operators
for
most
ofyour
classes,
so
the
process
is
worth
memorizingSuggestsOperatormended
useMembermustbe
memberAll
unary
operators= (
) []
–>+=
–=/=
*=
^=&=
|=
%=
>>=
<<=All
other
binaryoperatorsnon-memberObject-Oriented
ProgrammingObject-Oriented
ProgrammingIncrement
&
decrement
(++
/
-
-)在C++中,單目前綴增(減)和后綴增(減)都用++和--運(yùn)算符來表示,編譯器為了區(qū)分它們規(guī)定:后綴增(減)函數(shù)應(yīng)帶有一整型量,這種參量僅僅用來區(qū)分前后綴,調(diào)用時,不必顯式給出,它的缺省值為0。前綴++:后綴++:前綴--:后綴--:++a
<==>
a.operator++()
//前綴增函數(shù)a++
<==>--a
<==>a--
<==>a.operator
++(0)a.operator
--()a.operator
--(0)c12\counter//后綴增函數(shù)Unusual
operators
overloadingObject-Oriented
Programming[]
=
() ->
must
be
overloaded
as
a
member
function二目運(yùn)算符[],通常用它來定義對象的下標(biāo)操作,第一個操作數(shù)必須是該類的對象。故只能重載為類的成員對象。Three/operator=/int-Array.cppObject-Oriented
ProgrammingBecause
assigning
an
object
to
another
object
of
the
same
type
isanactivity
most
people
expect
to
be
possible,
the
compiler
will
automaticallycreate
a
type&
type::operator=(const
type&)
;Default
Policy:
bitcopyIf
you
don’t
make
one.
The
behavior
of
this
operator
mimics
that
ofthe
automatically
created
copy-constructor;Assignment
operator
=
overloadingObject-Oriented
ProgrammingObject-Oriented
ProgrammingObject-Oriented
ProgrammingObject-Oriented
ProgrammingObject-Oriented
ProgrammingMemberwise
Assignment(成員賦值)if
the
class
contains
subobjects(or
is
inherited
from
another
class),
theoperator=
for
those
subobjects
is
called
recursively.
This
is
calledmemberwise
assignment.Handle
assignment
to
self
in
operator=MemberwiseObject-Oriented
Programming拷貝構(gòu)造函數(shù)和賦值函數(shù)非常容易 ,常導(dǎo)致錯寫、錯用??截悩?gòu)造函數(shù)是在對象被創(chuàng)建時調(diào)用的,而賦值函數(shù)只能被已經(jīng)存在了的對象調(diào)用。String
a(“
o”);String
b(“world”);String
c
=
a;//調(diào)用了拷貝構(gòu)造函數(shù),最好寫成c(a);c
=
b;//調(diào)用了賦值函數(shù)本例中第三個語句的風(fēng)格較差,宜改寫成String
c(a)以區(qū)別于第四個語句。Copy
constructor
VS
operator=Object-Oriented
ProgrammingObject-Oriented
Programming編譯器生成缺省函數(shù)時,可以了解大量關(guān)于需要處理的工作和可以產(chǎn)生優(yōu)良代碼的工作。這種代碼通常比用戶編寫的代碼的執(zhí)行速度快,原因是編譯器可以利用匯編級功能的優(yōu)點,而程序員則不能利用該功能的優(yōu)點。缺省函數(shù)是內(nèi)聯(lián)函數(shù)。-例如:定義fraction類,使用編譯器生成的賦值操作,拷貝操作,缺省析構(gòu)函數(shù)?!疽?guī)則】盡可能使用編譯器隱式生成的函數(shù)【規(guī)則】為需要動態(tài)分配內(nèi)存的類重載
拷貝構(gòu)造函數(shù),析構(gòu)函數(shù)和賦值運(yùn)算符重載-只要類里有指針時,就要寫自己版本的拷貝構(gòu)造函數(shù)和賦值運(yùn)算符重載。在這些函數(shù)里,你可以拷貝那些被指向的數(shù)據(jù)結(jié)構(gòu),從而使每個對象都有自己的拷貝。-對于有些類,根據(jù)實際應(yīng)用,可以確定程序中不會做拷貝和賦值操作的時候,可以只
這些函數(shù)( 為private成員)而不去定義(實現(xiàn))它們。Object-Oriented
ProgrammingOverloading
global
new
and
deleteObject
*p
=
new
Object;//
two
things
occur.Overloading
new
and
delete,
storage
is
allocated
using
the
operator
new,then
the
constructor
is
called.delete
p;
//
two
things
occur.,
the
destructor
is
called,then
storage
is
deallocated
using
the
operator
delete.The
constructor
and
destructorcalls
are
never
under
your
control,Object-Oriented
ProgrammingObject-Oriented
ProgrammingOverloading
global
new
and
deleteThe
constructor
and
destructor
calls
are
never
under
your
control,
butyou
can
change
the
storageallocation
functions
operator
new
and
operator
delete.overloading
new
&
delete
for
a
classmemory/GlobalOperatorNew.cppObject-Oriented
ProgrammingClassOperator
overloadingAutomatic
type
conversionInheritance
&
CompositionPolymorphism
&
Virtual
FunctionsThe
C
in
C++Object-Oriented
ProgrammingOld
style
castsImplicit
type
conversionl-value
=
expression;Actual
parameters
-->
Formal
parametersExplicit
type
conversionl-value
=
(
type
)
expression
;l-value
=
type(
expression
);3.3
Automatic
type
conversionthree/cast/cast.cpp擴(kuò)大轉(zhuǎn)換:從一種類型轉(zhuǎn)換成另一種類型時,如果后者至少能和前者相同范圍的值,發(fā)生的就是“擴(kuò)大轉(zhuǎn)換”。收縮轉(zhuǎn)換:如果后者能
的值的范圍小于前者,發(fā)生的是“收縮轉(zhuǎn)換”O(jiān)bject-Oriented
ProgrammingExplic
s
should
be
used
carefully,
becausewhat
you
areactually ng
is
saying
to
the
compiler
“F et
type
checking
–
treat
it
asthis
other
type
instead.”
That
is,
you’re
introducing
a
hole
in
the
C++
typesystem
and
preventing
the
compiler
from ling
you
that
you’re
ngsomething
wrong
with
a
typeMinimize
castingObject-Oriented
ProgrammingStandard
C++
includes
an
expliccomple y
replace
the
old
C-style
casts
.syntax
that
can
be
used
toC++
Style
Castsstatic_castdynamic_castconst_castreinterpret_castthree/cast/cast.cppstatic_cast<T>(v)將表達(dá)式v
的值轉(zhuǎn)換為T
類型。該表達(dá)式可用于任何隱式允許的轉(zhuǎn)換類型。如果類型轉(zhuǎn)換與舊樣式一樣合法,則任何隱式轉(zhuǎn)換都可以反向轉(zhuǎn)換。For
exampleenum
E{ =1,
second=2,third=3};
int
i=second;//隱式轉(zhuǎn)換E
e=static_cast<E>(i);//反向隱式轉(zhuǎn)換Object-Oriented
Programmingconst_cast<T>(v)可用于更改指針或 的
const
或
volatile限定符。(在新樣式的類型轉(zhuǎn)換中,只有const_cast<>可以去掉const限定符。)或指向成員的指針的類型。T
必須是指針、For
exampleObject-Oriented
Programmingclass
A{public:void
f();int
i;};extern
const
volatile
int*
cvip;extern
int*
ip;void
use_of_const_cast(
){const
A
a1;const_cast<A&>(a1).f();//去掉constip=const_cast<int*>(cvip);//去掉const
和volatile}Object-Oriented
Programmingvolatile修飾符告訴編譯程序不要對該變量所參與的操作進(jìn)行優(yōu)化.在兩種特殊的情況下需要使用volatile修飾符:-第一種情況涉及到內(nèi)存
硬件(memory-mapped
hardware,如圖形適配器,這類設(shè)備對計算機(jī)來說就好象是內(nèi)存的一部分一樣)。-第二種情況涉及到共享內(nèi)存(sharedmemory,既被兩個以上同時運(yùn)行的程序所使用的內(nèi)存)。Object-Oriented
ProgrammingObject-Oriented
Programmingreinterpret_cast<T>(v)把數(shù)據(jù)v以二進(jìn)制存在的形式,重新解釋成另一種類型T的值。
reinterpret_cast允許任意的類型裝換,包括將指針轉(zhuǎn)換為整數(shù),將整數(shù)轉(zhuǎn)換為指針,以及將常量轉(zhuǎn)換為非常量等For
exampleint
*pi
=reinterpret_cast<int*>(i);將整數(shù)i的值以二進(jìn)制(位模式)的方式被解釋為整數(shù)指針,并賦給piint
j=reinterpret_cast<int>(pi);將指針pi的值以二進(jìn)制(位模式)的方式被解釋為整型,并賦給jthree/cast/AutomaticTypeConversion.cppObject-Oriented
ProgrammingIf
you
define
a
constructor
that
takes
as
its
single
argument
an
object
(orreference)
of
another
type,
that
constructor
allows
the
compiler
to
performan
automatic
type
conversion.Constructor
conversion“explicit”
key
wordexplicit
complex(doublerp)
:
rpart(rp),ipart(0){cout
<<
"I
am
in
complex(double
rp)."
<<
endl;}c=a+4;
pile-time
errorc
=
a
+complex(4);Object-Oriented
ProgrammingOperator
conversionthree/cast/OperatorConversion.cppObject-Oriented
ProgrammingObject-Oriented
ProgrammingThe
second
way
to
produceautomatic
type
conversion
is
throughoperator
conversion.
Youcan
create
a
member
function
that
takesthe
current
type
and
converts
it
to
the
desired
type
using
the
operatorkeyword
followed
by
the
type
you
want
to
convert
to.
This
form
of
operatoroverloading
is
unique
because
you
don’t
appear
to
specify
a
return
type–the
return
type
is
the
name
of
the
operator
you’re
overloading.實現(xiàn)自動類型轉(zhuǎn)換要注意的問題:二義性O(shè)bject-Oriented
ProgrammingSolution
:Just
provide
asingle
path
for
automaticconversion
from
one
type
toanother實現(xiàn)自動類型轉(zhuǎn)換要注意的問題:二義性O(shè)bject-Oriented
Programming如果要實現(xiàn)從用戶定義類型向內(nèi)置類型轉(zhuǎn)換,必須使用OperatorconversionObject-Oriented
Programming盡量使用
(&)傳遞對象恰當(dāng)使用inline函數(shù)避免
(臨時)對象使用The
return
optimization(返回效率)提高程序性能Object-Oriented
Programming在代碼中真正的臨時對象是看不見的,它們不出現(xiàn)在你的源代碼中。這種未命名的對象通常在兩種條件下產(chǎn)生:為了使函數(shù)成功調(diào)用而進(jìn)行隱式類型轉(zhuǎn)換和函數(shù)返回對象時。理解如何和為什么建立這些臨時對象是很重要的,因為構(gòu)造和
它們的開銷對于程序的性能來說有著不可忽視的影響。通常有兩個方法可以消除它。一種是重新設(shè)計你的代碼,不讓發(fā)生這種類型轉(zhuǎn)換。另
法是通過修改 而不再需要類型轉(zhuǎn)換。避免
(臨時)對象Object-Oriented
Programming在代碼中,臨時對象的創(chuàng)建和銷毀會占用很多處理時間和內(nèi)存。您編寫的函數(shù)要將臨時對象的數(shù)目減少到理解程序所需的最小數(shù)目。這些技術(shù)包括:使用顯式變量而不使用隱式臨時對象;使用參數(shù)而不使用值參數(shù);使用返回值優(yōu)化技術(shù);另外一種技術(shù)是實現(xiàn)和使用諸如+=這樣的操作,而不實現(xiàn)和使用只包含+和=的操作。例如,下面的第一行引入了a+b結(jié)果的臨時對象,而第二行則不是。complexx=a+b;complex
x(
a)
;
x
+=
b
;Object-Oriented
ProgrammingCode
ysis-首先,temp對象被創(chuàng)建,與此同時它的構(gòu)造函數(shù)被調(diào)用。-然后,拷貝構(gòu)造函數(shù)把temp拷貝到返回值外部
單元里。-最后,當(dāng)temp在作用域的結(jié)尾時調(diào)用析構(gòu)函數(shù)。The
return
optimization(返回效率)complex
temp(x.rpart+y.rpart,x.ipart+y.ipart);return
temp;Object-Oriented
ProgrammingCode
ysis-編譯器直接地把這個對象創(chuàng)建在返回值外面的內(nèi)存單元。因為不是真正創(chuàng)建一個局部對象,所以僅需要單個的普通構(gòu)造函數(shù)調(diào)用(不需要拷貝構(gòu)造函數(shù)),效率提高了。return
complex(x.rpart+y.rpart,x.ipart+y.ipart);Object-Oriented
ProgrammingObject-Oriented
ProgrammingClassOperator
overloadingAutomatic
type
conversionInheritance
&
CompositionPolymorphism
&
Virtual
FunctionsThe
C
in
C++In
C++,Code
Reuse-instance
reuse-entrust(using
member
object)-inheritance3.4
Composition
&
Inheritanceposition/consign1.cpp~consign3.cppObject-Oriented
ProgrammingSubobject-When
an
object
is
created,
the
compiler
guarantees
thatconstructors
for
all
of
its
subobjects
are
called.-memberwise
initializingComposition-Member
Objectposition/object
member.cppObject-Oriented
ProgrammingObject-Oriented
Programmingclass
B{private:
float
z;Am;//member
subobjectpublic:
B() {z
=0.0;}B(int
r1,int
r2,float
r):m(r1,r2){ z=r;
}};Constructor
initialization
listB(
)
:
m(
)
//leave
out:m(){
z
=0.0;}Object-Oriented
ProgrammingB
b;
call
A(…)-->callB(…)Object-Oriented
ProgrammingThis
isespecially
critical
when
initializing
const
and
reference
datamembers
because
they
must
be
initialized
before
the
function
bodyisentered.To
make
the
syntax
consistent,
you
are
allowed
to
treat
built-in
typesas
if
they
have
a
single
constructor,
Thus,
you
can
say:About
Constructor
initialization
listObject-Oriented
ProgrammingMember
object
initialization
sequence
isconsistent
with
theirdeclared
order
in
the
class.
has
nothing
to
do
with
listed
order
in
theconstructor
initialization
list.to
see:<effective
C++>item
13Use
Constructor
initialization
list
if
you
can.Inheritance:
A
mechanism
express
a
particular
layer
of
the
objectsandother
objects.Automatic
inherit
the
father
operations
and
datassupport
incremental
developmentInheritanceUnit
three/employeeObject-Oriented
ProgrammingObject-Oriented
ProgrammingIncremental
developmentprogram
development
is
an
incremental
process,
just
like
human
learning.inheritance
support
incremental
development
by
allowing
you
to
introducenew
code
without
causing
bugs
in
existing
code.
A
base
type
contains
all
ofthe
characteristics
and
behaviors
that
are
shared
among
the
types
derivedfrom
it.
You
create
a
base
type
to
represent
the
core
of
your
ideas
aboutsome
objects
in
your
system.
From
the
base
type,
you
derive
other
types
toexpress
the
different
ways
that
this
core
can
be
realized.繼承的優(yōu)點之一是它支持漸增式開發(fā),它允許
在已開發(fā)的代碼中引進(jìn)新代碼,而不會給源代碼帶來錯誤,即使產(chǎn)生了錯誤,這個錯誤也只是與新代碼有關(guān)。也就是說當(dāng)
繼承已存在的功能類并對其增加數(shù)據(jù)成員和成員函數(shù)(并重定義已存在的成員函數(shù))時,已存在類的代碼并不會被改變,更不會產(chǎn)生錯誤。如果出現(xiàn)錯誤, 就會知道它肯定在 的新代碼中。相對于修改已存在代碼體的做法來說,這些新代碼很短也很容易讀。認(rèn)識到程序開發(fā)是一個漸增過程,就像人的學(xué)習(xí)過程一樣,這是很重要的。我們做盡可能多的分析,但當(dāng)開始一個項目時, 仍不可能知道所有的答案。如果開始把項目作為一個有機(jī)的、可進(jìn)化的生物來“培養(yǎng)”,而不是完全一次性的構(gòu)造它, 就會獲得更大的成功和更直接的反饋。Object-Oriented
ProgrammingInheritance
syntaxclass
derivedClass :[public
|
protected
|
private]
baseClass{
//difference
parts
between
base
and
derived;}
;①Adding
data
members
and
member
functions②Redefining
existing
member
functions
during
inheritanceObject-Oriented
Programmingmanager
m(“su
san
”,
48,
7000,
3);Object-Oriented
ProgrammingObject-Oriented
ProgrammingWhen
an
object
is
created,
the
compiler
guarantees
that
constructors
for
allof
its
subobjects
are
called.,The
solution
is
simple:
Call
the
constructor
for
the
subobject.
C++provides
a
special
syntax
for
this,
the
constructor
initializer
list.Constructor
and
Destructor
of
the
derived
classpublicA
//father
Anonymity
subobjectclass
C
:{
private:B m;
//guest
member
subobjectint
i;};C(parameter
list1
declarations,parameter
list2
declarations,Object-Oriented
Programmingparameter
list3
declarations)
:A(parameter
list1
),m(parameter
list2
){//initialize
parameter
list3;}Object-Oriented
Programmingconstruction
starts
at
the
very
root
of
the
class
hierarchy,
and
that
at
eachlevel
the
base
class
constructor
is
called ,
followed
by
the
emberobject
constructors.
The
destructors
are
called
in
exactly
the
reverse
orderof
theconstructors.the
order
of
constructor
calls
for
member
objects
is
comple y
unaffectedby
the
order
of
the
calls
in
the
constructor
initializer
list.
The
order
isdetermined
by
the
order
that
the
member
objects
are
declared
in
the
class.Order
of
constructor
&
destructor
callsUnit
three/Inheritance/Order.cppOrder
of
constructorfather→then
guest->finally
myselfOrder
of
destructorFinally
father??then
guest??
myselfObject-Oriented
ProgrammingObject-Oriented
ProgrammingAutomatic
destructor
calls-there’s
only
one
destructor
for
any
class,
and
it
guaranteed
clean
up
fortheir
particular
class
.
you
never
need
to
make
explicit
destructor
calls-the
compiler
ensures
that
all
destructors
are
called,
and
that
means
all
ofthe
destructors
in
the
entire
hierarchy,
starting
with
the
most-deriveddestructor
and
working
back
to
the
root.Object-Oriented
Programming在繼承層次中構(gòu)造函數(shù)和析構(gòu)函數(shù)的行為默認(rèn)構(gòu)造函數(shù)(無參構(gòu)造函數(shù))的重要性析構(gòu)函數(shù)的調(diào)用時機(jī)當(dāng)對象被創(chuàng)建和銷毀時,處理內(nèi)存的方式設(shè)計一個派生類需特別關(guān)注的地方Protected
Access
protectionvoid
manager::print_level(){print();
//√cout<<level<<endl;
//
√cout<<name<<endl;
//
×}Object-Oriented
ProgrammingObject-Oriented
ProgrammingPublic
Membervisible
to
self
and all
clientsProtected
Membervisible
to
self
and
classes
derived
from
self
andto
friendsPrivate
Membervisible
only
to
self
and
to
friends!Access
Protectionone
class
can
derive
many
subclass。One
subclass
can
derive
continuallysub-subclass……在繼承中,派生類幾乎繼承了基類的所有特征,因而在定義一組類時,將其公共屬性抽取出來,放在基類中,就可以避免在每個類中重寫基類的代碼。在派生類中利用重定義函數(shù)修改基類行為進(jìn)一步增加了重用的靈活性,為重用帶來了方便。Inheritance
hierarchyObject-Oriented
Programmingbase
class
intoNot
all
functithe
derived
class.destruction
of
ancreation
andthe
aspects
ofrs
anddestructors
in
theoCoh,
constructorsand
destructors
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 《戰(zhàn)略更新課件:引領(lǐng)企業(yè)未來》
- 2025年江西省南昌市中考物理一調(diào)試卷(解析版)
- 合同終止時的員工權(quán)益
- 數(shù)據(jù)庫技術(shù)COMPUTER課件
- 鐵路橋隧無損檢測任務(wù)三隧道檢測的內(nèi)容課件
- 鐵路市場營銷市場定位的涵義課件
- 鐵路信號與通信設(shè)備接發(fā)列車工作31課件
- 中醫(yī)灸法技能培訓(xùn)班課件
- 中專文化課課件
- 發(fā)酵類制藥工業(yè)水污染物間接排放標(biāo)準(zhǔn)DB41 758-2012
- 2025年中考?xì)v史復(fù)習(xí)專項訓(xùn)練:中國近代史材料題40題(原卷版)
- 2024年手工木工職業(yè)技能競賽理論考試題庫-下(多選、判斷題)
- 2024上半年浙江杭州市臨平區(qū)機(jī)關(guān)事業(yè)單位編外用工招聘61人歷年高頻500題難、易錯點模擬試題附帶答案詳解
- 有限空間作業(yè)氣體檢測記錄表
- 八年級語文上冊 第一單元 第3課《鄉(xiāng)愁 余光中》教案 冀教版
- 2024中考英語必考1600詞匯分類速記表
- 小學(xué)語文課程方案2022
- DL∕T 1709.3-2017 智能電網(wǎng)調(diào)度控制系統(tǒng)技術(shù)規(guī)范 第3部分:基礎(chǔ)平臺
- 化妝品生產(chǎn)OEM合同書
- 幼兒園課件:《動物的尾巴》
評論
0/150
提交評論