




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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)?當創建complex類的對象a時,以complex類定義為樣板建立a的相應的數據成員,但它并不為對象a從complex類定義中拷貝所定義的操作代碼。也就是:
complex類定義中的成員函數代碼 在某塊公用的
空間中,供該類的所有對象共享---代碼共享。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指向的是一片未初始化的空間。第二步,調用構造函數Complex()來初始化this指向的區域,也就是對象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方法可以控制返回給客戶的數據格式。set方法可以檢查對private變量值進行修改的企圖,確保新值對那個數據成員來說是合適的、完整的、一致的。條款18:to
make
the
class
interface
is
complete
andminimal(Effective
C++)Object-Oriented
Programming它使程序從
工程的角度看顯得更具有
。set和get方法雖然提供了對private數據的 ,但通過控制這些
器的實現,就能控制客戶代碼能對數據進行什么操作。能在類的客戶面前隱藏數據成員的
表示方式。因此,如果數據的表示方式發生改變(通常是為了減少所需的
空間,或者為了改進性能),那么只需修改方法的實現,客戶端的實現則無需更改---只要方法提供的接口予以保留。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++預定義類型(char、int、float等)的操作用運算符來表示,其調用形式是表達式,中綴性式:a+b
,前綴形式:++a,后綴形式:a++。用戶定義的類型的操作則用函數表示,對它采用顯式調用。為了使用戶定義的類型與系統預定義類型相一致,也允許對用戶定義的類型使用運算符來表示操作,如set1+set2,matrix1*matrix2。這種一致性還表現在可以為用戶定義的類型提供初始化、賦值以及轉換規則等。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).成員函數版_complex友員函數版_complexC++中的友員相當于為封裝隱藏這堵不透明的墻開了一個小孔,任何該類的朋友可以通過這個小孔窺視該類的私有數據。注意友員函數與成員函數的區別:友員函數在類中
,但不是該類的成員函數,不能通過this指針調用。friendObject-Oriented
Programming象程序設計風格的性變差。在以下使用全局友員函數是不恰當的。它破壞了面一致性,使數據封裝性受到削弱,導致程序的可情況發生,考慮使 員函數:-在類的設計中沒有為類定義完整的操作集,將友員函數作為對類的操作的一種補充形式。-考慮運行效率。Friend-
函數
-
成員函數
-
類Object-Oriented
ProgrammingObject-Oriented
ProgrammingDeclare
non-member
functions
when
type
conversions
should
applyto
all
parameters.[若所有參數皆需類型轉換,請為此采用non-member函數重載]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
成員函數版/Unary.cpp
友員版C12:Integer.h/Integer.cpp/IntegerTest.cpp友員版
Byte.h成員函數版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++中,單目前綴增(減)和后綴增(減)都用++和--運算符來表示,編譯器為了區分它們規定:后綴增(減)函數應帶有一整型量,這種參量僅僅用來區分前后綴,調用時,不必顯式給出,它的缺省值為0。前綴++:后綴++:前綴--:后綴--:++a
<==>
a.operator++()
//前綴增函數a++
<==>--a
<==>a--
<==>a.operator
++(0)a.operator
--()a.operator
--(0)c12\counter//后綴增函數Unusual
operators
overloadingObject-Oriented
Programming[]
=
() ->
must
be
overloaded
as
a
member
function二目運算符[],通常用它來定義對象的下標操作,第一個操作數必須是該類的對象。故只能重載為類的成員對象。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拷貝構造函數和賦值函數非常容易 ,常導致錯寫、錯用。拷貝構造函數是在對象被創建時調用的,而賦值函數只能被已經存在了的對象調用。String
a(“
o”);String
b(“world”);String
c
=
a;//調用了拷貝構造函數,最好寫成c(a);c
=
b;//調用了賦值函數本例中第三個語句的風格較差,宜改寫成String
c(a)以區別于第四個語句。Copy
constructor
VS
operator=Object-Oriented
ProgrammingObject-Oriented
Programming編譯器生成缺省函數時,可以了解大量關于需要處理的工作和可以產生優良代碼的工作。這種代碼通常比用戶編寫的代碼的執行速度快,原因是編譯器可以利用匯編級功能的優點,而程序員則不能利用該功能的優點。缺省函數是內聯函數。-例如:定義fraction類,使用編譯器生成的賦值操作,拷貝操作,缺省析構函數。【規則】盡可能使用編譯器隱式生成的函數【規則】為需要動態分配內存的類重載
拷貝構造函數,析構函數和賦值運算符重載-只要類里有指針時,就要寫自己版本的拷貝構造函數和賦值運算符重載。在這些函數里,你可以拷貝那些被指向的數據結構,從而使每個對象都有自己的拷貝。-對于有些類,根據實際應用,可以確定程序中不會做拷貝和賦值操作的時候,可以只
這些函數( 為private成員)而不去定義(實現)它們。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擴大轉換:從一種類型轉換成另一種類型時,如果后者至少能和前者相同范圍的值,發生的就是“擴大轉換”。收縮轉換:如果后者能
的值的范圍小于前者,發生的是“收縮轉換”Object-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)將表達式v
的值轉換為T
類型。該表達式可用于任何隱式允許的轉換類型。如果類型轉換與舊樣式一樣合法,則任何隱式轉換都可以反向轉換。For
exampleenum
E{ =1,
second=2,third=3};
int
i=second;//隱式轉換E
e=static_cast<E>(i);//反向隱式轉換Object-Oriented
Programmingconst_cast<T>(v)可用于更改指針或 的
const
或
volatile限定符。(在新樣式的類型轉換中,只有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修飾符告訴編譯程序不要對該變量所參與的操作進行優化.在兩種特殊的情況下需要使用volatile修飾符:-第一種情況涉及到內存
硬件(memory-mapped
hardware,如圖形適配器,這類設備對計算機來說就好象是內存的一部分一樣)。-第二種情況涉及到共享內存(sharedmemory,既被兩個以上同時運行的程序所使用的內存)。Object-Oriented
ProgrammingObject-Oriented
Programmingreinterpret_cast<T>(v)把數據v以二進制存在的形式,重新解釋成另一種類型T的值。
reinterpret_cast允許任意的類型裝換,包括將指針轉換為整數,將整數轉換為指針,以及將常量轉換為非常量等For
exampleint
*pi
=reinterpret_cast<int*>(i);將整數i的值以二進制(位模式)的方式被解釋為整數指針,并賦給piint
j=reinterpret_cast<int>(pi);將指針pi的值以二進制(位模式)的方式被解釋為整型,并賦給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.實現自動類型轉換要注意的問題:二義性Object-Oriented
ProgrammingSolution
:Just
provide
asingle
path
for
automaticconversion
from
one
type
toanother實現自動類型轉換要注意的問題:二義性Object-Oriented
Programming如果要實現從用戶定義類型向內置類型轉換,必須使用OperatorconversionObject-Oriented
Programming盡量使用
(&)傳遞對象恰當使用inline函數避免
(臨時)對象使用The
return
optimization(返回效率)提高程序性能Object-Oriented
Programming在代碼中真正的臨時對象是看不見的,它們不出現在你的源代碼中。這種未命名的對象通常在兩種條件下產生:為了使函數成功調用而進行隱式類型轉換和函數返回對象時。理解如何和為什么建立這些臨時對象是很重要的,因為構造和
它們的開銷對于程序的性能來說有著不可忽視的影響。通常有兩個方法可以消除它。一種是重新設計你的代碼,不讓發生這種類型轉換。另
法是通過修改 而不再需要類型轉換。避免
(臨時)對象Object-Oriented
Programming在代碼中,臨時對象的創建和銷毀會占用很多處理時間和內存。您編寫的函數要將臨時對象的數目減少到理解程序所需的最小數目。這些技術包括:使用顯式變量而不使用隱式臨時對象;使用參數而不使用值參數;使用返回值優化技術;另外一種技術是實現和使用諸如+=這樣的操作,而不實現和使用只包含+和=的操作。例如,下面的第一行引入了a+b結果的臨時對象,而第二行則不是。complexx=a+b;complex
x(
a)
;
x
+=
b
;Object-Oriented
ProgrammingCode
ysis-首先,temp對象被創建,與此同時它的構造函數被調用。-然后,拷貝構造函數把temp拷貝到返回值外部
單元里。-最后,當temp在作用域的結尾時調用析構函數。The
return
optimization(返回效率)complex
temp(x.rpart+y.rpart,x.ipart+y.ipart);return
temp;Object-Oriented
ProgrammingCode
ysis-編譯器直接地把這個對象創建在返回值外面的內存單元。因為不是真正創建一個局部對象,所以僅需要單個的普通構造函數調用(不需要拷貝構造函數),效率提高了。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.繼承的優點之一是它支持漸增式開發,它允許
在已開發的代碼中引進新代碼,而不會給源代碼帶來錯誤,即使產生了錯誤,這個錯誤也只是與新代碼有關。也就是說當
繼承已存在的功能類并對其增加數據成員和成員函數(并重定義已存在的成員函數)時,已存在類的代碼并不會被改變,更不會產生錯誤。如果出現錯誤, 就會知道它肯定在 的新代碼中。相對于修改已存在代碼體的做法來說,這些新代碼很短也很容易讀。認識到程序開發是一個漸增過程,就像人的學習過程一樣,這是很重要的。我們做盡可能多的分析,但當開始一個項目時, 仍不可能知道所有的答案。如果開始把項目作為一個有機的、可進化的生物來“培養”,而不是完全一次性的構造它, 就會獲得更大的成功和更直接的反饋。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在繼承層次中構造函數和析構函數的行為默認構造函數(無參構造函數)的重要性析構函數的調用時機當對象被創建和銷毀時,處理內存的方式設計一個派生類需特別關注的地方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……在繼承中,派生類幾乎繼承了基類的所有特征,因而在定義一組類時,將其公共屬性抽取出來,放在基類中,就可以避免在每個類中重寫基類的代碼。在派生類中利用重定義函數修改基類行為進一步增加了重用的靈活性,為重用帶來了方便。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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 護坡安裝工程承包合同
- 加氣塊砌筑勞務分包合同協議書
- 出租汽車承包合同書
- 房地產委托合同協議
- 專利權轉讓合同簽訂指
- 墻紙拆除合同協議
- 合同協議斜線
- 種業加盟合同協議書范本
- 電車購車協議合同
- 內貿租船合同協議
- 華為MA5800配置及調試手冊
- 山東省濟寧市金鄉縣2023-2024學年八年級下學期4月期中考試數學試題
- 靜脈用藥調配中心課件
- (2024年)剪映入門教程課件
- 提升服務行業人員的職業道德和職業素養
- 眩暈診治中國專家共識解讀課件
- 按摩椅行業分析及市場前景展望報告
- 2024年上海外服招聘筆試參考題庫附帶答案詳解
- 關于設備性能評估報告
- 教育專家報告合集:年度得到:沈祖蕓全球教育報告(2023-2024)
- 化妝品研發與美容技術學習資料
評論
0/150
提交評論