




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、关键字 关键字 auto 关键字,现在有例如推断数据类型从表达式或 auto 变量而来对于编译时间的断言。对模板和有效性不能使用宏#ifdefLambda 表达式 逻辑定义的函数。从函数指针和类对象中继承 Trailing 返回类型 但模板的返回类型不能够表达式,是很有用的 C+ 语言的特性一定被包含在VC8 和VC9 (+ . 被整理到C+0 x中介码名字已经改为C+0 x, 许多编译器都已经介绍了它的一些特性。这个指南将尝试给你介绍 C+ 语言的新特性。请注意,尽管这些特性已经应用到其他的编译器上,但我只在 Visual C+ 2010 编译器上解释一些新的特性。在其他编译器上C+的新特性
2、以下列表是我将要 的 C+ 语言增加的一些新特性。我已经 的强调了lambdas 和 R-values这两个新名词暂时没有合适的汉语翻译)了,由于我还没有在哪里找到任何可消化的现在,编译器就不知道变量nResult 的类型,使用auto关键字*,由于nVariablenVariable3autonVariable5=/被推论的 double, 因为 sqrt 接受 3 不同的数据类型,但传入double,覆盖返回值/ autonVariable=/错误,因为 sqrt的调用的/ 这个错误与 auto 关键字不相关autonVariable15654autonVariable21003; aut
3、onVariable3 1003.0double类型的推论由于编译器把整个表达式作 它将产生一个错误。这不像是Visual Basic 或web几个例子autonVariable/Compiler/errorC3531:nVariable:asymbolwhosetypeautoveannVariable=autonVariable=structautoVariable=/ error C2864: AutoStruct:Variable : 只有静态只读的成员变量才可在结构体或类中structautoVariable=/ error C2864: AutoStruct:Variable :
4、只有静态只读的成员变量才可在结构体或类中如果你需要一个 auto的返回类型或auto 你不能在 类class或结构体struct中使用autoautovoidArgumentDeduction(auto/ C3533: auto: 参数类型的变量不能够包含不允许的情景autoauto/ error C3532: 数组类型的的元素的类型不能定义为包含 constautoPI=3.14; /volatileautoIsFinished=false; /constautonStringLen=constvolatile修饰符autoiArray=10;new操作符auto&pVariable=nVa
5、riable1; /是的,又该这个变量的值,将修改的变量autopVariable=&pVariable6;auto*pVariable7=&nVariable1;位很确定的事情你可以使用 size_t代 或 64 std:vectorStrings;/string位很确定的事情你可以使用 size_t代 或 64 std:vectorStrings;/string/Pushseveral2autonLength=strlen(Theauto nLength=strlen(Theauto翼翼。 如果你不幸,只有一个变量使用了auto产生C3538的错误(如上)因此什么时候应该真正的使用 aut
6、o关键字呢 ForautonVariable= float ,但实际上为double。autonVariable=sqrt(100.0),nVariableX=autoa=10,b=10.30,errorC3538:在一个declarator-list,string,string,string:const_iteratorm_iter=/ cbegin使用的情况下,迭代器总是只读的for(autoiter=Strings.cbegin();iter!=Strings.cend();+iter)的对象上调用 begin方法时, 你不能够再将它分到一个非只读的iterator 上, 一样, 因为我
7、不是在写STL, 请自己阅读并做相关实验)概括了所有的复杂性,并且引进了autoC+STL cbegin, cend, crbegincrend方法提供了便利。C 前缀意思为只读。他们总是返回 const_iterator的迭代器,不管对象(容器)是否为const。老的方法依靠对象的常量/meusingfor(vector:const_iterator iter = Strings.begin();iter!=Strings.end();+iter)std:cout*iterstd:endl;会倾向于使用const_iterator来代替iteratorfor(autoiter=Strings
8、.begin();iter!=Strings.end();std:cout*iterstd:endl; 笨拙的。尽管可以选择使用关键字typedef在程序的某些地方来返回类型并且使用类型名。但是对于迭代器类型又有多少呢? 并且一个迭代器类型只用一次又会怎样呢?如此显示出它for(std:vector:iterator iter = Strings.begin();iter!=Strings.end(); +iter) std:cout*iterstd:endl;autokeyword(typededuction)-decltype(nVariable1)翻译成 类型。decltype关键字与t
9、ypeid关键autokeyword(typededuction)-decltype(nVariable1)翻译成 类型。decltype关键字与typeid关键字不同。 autoxVariable=typeid(nVariable1)nVariable2为一 decltype(nVariable1) decltype 关键为变量分配一个 Lambdas(以下文章是关于lambdas的解释。为返回类型指定一个 尽管不涉及表达式语法是必须的。我将程式后它外部autom_iter=外部参考decltype decltype(1/0) Infinite; / 0的情况,编译器并不产/程序不会 exi
10、t, 会保存 exit(0), 的类型/在不进行函数调用的情况下指定exit 会使得MyExitFunction 的返回类型有所不decltype(exit(0)使用auto从右边的表达式上推论出类型,的去推论类型。使用 decltype,你不需要指定变量,仅仅 在上面的第二个例子中,mstr 是std:map 对象, 取回迭代器,即为 map 元素的第二个成员,并最终为它的分配器类型。因此,为string 推断出 std:allocator 类型(请看上面,mstr被 )。decltype(Strings.begin() string_iterator; decltype(xVariable
11、)decltype(SomeFunc) yVar; 假设xVariable(实际上,为SomeFunction的返回类型)的类型是现在,你不能再次nullptr 关键字-(使用/clr 选项编译器要求是错误的.nullptr 关键字-(使用/clr 选项编译器要求是错误的.MSDN 没有更新, 写这篇文章之时Externalvoidvoidfx(nullptr);/调用 /调用 请记住,nullptr是一个关键字,不是类型。因此,对于它你不能使用操作符sizeof或 ,NULL宏和关键字nullptr是不同的两个实体。NULL就是0,其例如void*pBuffer=if(pBuffer=nul
12、lptr /Dosomethingwithnull-ercase/Withvoidif(this !=.关键字是要知道,关键字不但用于本地 C+, 而且应用于托管的代码中。如果你以混合的模式使用 C+, 你可以显式的的使用关键字 nullptr来陈述本地空指针,并且使用nullptr表示托管空指针。即使在混合的模式下编程,你不会常使用 nullptr。error C2466:不能够分配固定大小为0 的数外部ic_assert 关键字-(Lambda)表达式由于任何一个指针类型的大小是相同的,当选择目标 做编译时。在早期的编译器中, 需要使用_S IC_ASSERT,尽管它不会做任何事情,但是
13、了数组的大小状况。因此,如果条件为真,它将 大小为 1error C2466:不能够分配固定大小为0 的数外部ic_assert 关键字-(Lambda)表达式由于任何一个指针类型的大小是相同的,当选择目标 做编译时。在早期的编译器中, 需要使用_S IC_ASSERT,尽管它不会做任何事情,但是 了数组的大小状况。因此,如果条件为真,它将 大小为 1的数组;如果条件为假它将 大小为 0 的数组这将导致编译器产生一个错误。错误通常不是友好的。ic_assert(sizeof(void*)=Thiscodeshouldonlybecompiledas32-errorC2338:Nineisnot
14、equaltoic_assert(10=9,Nineisnotequalto器会产生一个C2338 的错误提示。例如:ic_assert(,ic_assert 关键使用则了吗到一个局部变量pi中通常, 你). pi=return3.14159;(); std:cout pi;了吗到一个局部变量pi中通常, 你). pi=return3.14159;(); std:cout n2)?(n1): (56,nMin= return(n1doublereturn3.14159;Q. 关于返回值是什呢生错误生错误class TestClass函数不止一个返回表达式会是什么情况呢-doublereturn
15、3.14159;(); /()-autopi=returnautonSum= returnn1+n2+n3;autoxVal=(floatx)-float t; return ()-floaterrorC2090:()-autoerrorC3558*:const_iterator& x)-decltype(x);/Deducingtype of否把一个函需要做一些事情,如显示一个值,执行别的一些指令将会是怎样的呢?我能到一个已经定义的函数中,并在一些地方再次使用一函数被定义成一个局部函数,能否穿越函数作用域来使用呢?让函if否把一个函需要做一些事情,如显示一个值,执行别的一些指令将会是怎样的呢
16、?我能到一个已经定义的函数中,并在一些地方再次使用一函数被定义成一个局部函数,能否穿越函数作用域来使用呢?让函if(!IsEven(45)std:coutif(n%2 = 0) returnTestClass test; ptr=n1)-*p=*p = n1; delete usingautoDisplayIfEven=n)-if(n%2=std:coutif(n%2=std:coutNumberisevenn; std:coutif(n%2=0)returntrue; else return false;void/调用它IsEven你会明白以下4条是继承至C+的优点private变量,你无,
17、 得命名空间的解决方案。因此std命名空间的范围对于DisplayIfEven是不可用的。一函数能否包含另外一函数或常规函数吗函数支持缺省参数吗coutCallinglambda.; /使用&你指定了所有的变量通auto/使用&你指定了所有的变量通autoResetAll=&()-/由于你是通a=b=c= 例 return(a+b+c)/ 不能修改任何变量的float x=例 a=10,b=20,std:cout Valueofa= a std:endl;不能够修aerrorC3491:aa是通过值来/不std:coutb/errorC3493:b不能够被隐式的捕因为没有缺省的捕获例 & 通v
18、ar var&var 通来捕获var。, 例 &,b;/(1)通。, 例 &,b;/(1)通b,c,&nSum; / (3通过值来捕获nSum为值捕获a4)所有通过值捕获,隐藏了 a因为 a现在是一个函数的参数,糟/ &或=必须首先出现(如果被指定a,b,c,& / 逻辑上与上述相似,但是出错的指定之前, 将 错误:/ 只有nSum是通=,nSum=如例4 所示,出第二个例子, 而所有的三个参数(a, b, c)的和被在nSum中。例 /通过值仅捕获a和 nSum=a,b/你还记得()对于无参数returnstd:coutSum:void / ()是必须的,指定一个 mutable关键字因为所
19、有变量都是在通过值调用的模式下捕编译器会产生y,z均未使/ x的值依然为到现在, 已经看到了 可以防止一些变量 获,防止通过值的关键字为 const,防止通过 的关键字 non-const。因此,在上面的捕获类别中 已经覆盖了 1,2 4。捕constreference是不可能的(即,const&a)。 现在将会去研究一下最后一mutable 在参数说明括号后面, 指定了一个mutable关键字。 把所有通过值来捕获的变量放入一个通过值调用模式。如果 不放置一个mutable关键字,所有通过值来捕获的变量都是只读的,你不能在 函数中修改它。放置一个关键字 mutable就告诉编译器强制拷贝所的
20、通过值来捕获const 或非const 变量。 或者简单点,你可以假定他们通过传参的形式传入例如&,var除过var是通过值捕获的,其他均通=,&var-除过var是通var1var2 通过值来捕获变量var1var2 &var1,&var2 通来var1,var2var1,&var2 通过值来捕获var1来捕获var2&,a,c,nSum(2)b,&a&c&nSum(1相&无效&nSum,无效a,b,c,&无效tr1命名空间在技术 1 中,技术 1 被C+0 x 息。bool(tr1命名空间在技术 1 中,技术 1 被C+0 x 息。不能够在函数参数中使用/ 调用它在程序的某些地方用auto
21、关键字会更加的方便。这里有一些用例,然而,你在哪里必须使用一个function表达式时. 如下例:)sIsEven=n)-boolreturnn%2=函数与函数指针,函数对象有怎样的区别呢?函数的指针不保留状态,而 函数保留。通过 的捕获, 函数可以在调用期间保留它们 须严格遵守调用重载操作符()。更重要的是,你必须在函数块外面做这些工作以便于其他对于这个类应该调用 表达式的类型是什么呢表达式其实就是一些类。 你能够把它们在一个function类对象中。这个类,对于表达式,被定义在 std:tr1 命名空间中。让函voidstd:cout(n%2=函voidstd:cout(n%2=0)?Ye
22、s:/类对操作符classvoidstd:cout/调用指定的函数在 C+中介绍 表达式的目的是什么表达式对于许多STL 函数时非常有用的即函数要求一个函数指针或函数对象(使用 初,我没去覆盖STL 的函数,但是以一种简单的容易理解的形式解释了STL 的例子也许显得很多余,但却能够帮助澄清这个者 表达式应该是需要的类型,返回一个 void类型并且接受一个 类型的参数作为唯一,不应当拷贝函数voidTakeLambda(function&/只读voidTakeLambda(constfunction&完全限定voidTakeLambda(conststd:tr1:function&好! /传进一
23、个函数对class好! /传进一个函数对classnPredicate):Predicate(nPredicate)voidif(n std:cout LessnPredicate; std:coutnstd:coutn/ 传递一个函数指 传递一个函数对 /另式Callback obj; CallbackSomething(44,obj);/本地定义表达式CallbackSomething(59,std:coutHalf:因此,如果你把一个 obj对象传进多个CallbackSomething的调用(或者任何其他相似 的函数),它将拥有相同的断言(状态)。 就像你所了解的那样,这在函数指针中绝
24、对是不可能 使名表达式, autoeful = n)/通来捕获变量就 OK。当改n1000”Predicate=在有状态的变量autoeful = if(nstd:cout LessnPredicate; std:coutnCallbackSomething(59,eful);/n CallbackSomething(100,eful); /PredicateNOTchangedfor / 24 CallBack 构造函数的CallbackSomething!的参/式 就像我解释的怎样利用for_each函数来使用 表达式一样,你可以使用其他就像我解释的怎样利用for_each函数来使用 表达
25、式一样,你可以使用其他transform,generate,remove_if等等来使用它。 表达式不仅仅局限于使用STL 功能。他们也能够被很有效率的适用于任何你所需求的函数对象。你需要确保给他传递/n被通传递(与通捕获不相同for_each(Array,Array+10,&n)n*= 4;第一个调用调用IsEven函数,第二个调用调用 表达式,此表达式在for_each函数中 这是一个非常简单的例子,for_each和 表达式不需要写一个函数或类的情况下就可以被利用来能显示值。 值得肯定, 表达式能被进一步扩展用来做额外的工作如打印是个数是否为素数,或者计算求和(通过使用 调用),或修改一
26、个范围的元素。修改 表达式的形参对,是的,你能做到它,我一直在 通过 来捕获并做出修改,但是没有涵盖修改自身的参数。这个需求一直都没有出现直到现在。为了这样做,仅通过 (或指针)接受 表达式的Well, yes! You can dot. For long, I talked about taking captures by referen and making modifications, but did not cover modifying the argument itself. The needdidnotarisetillnow.Todothis,justtakethelambda
27、sparameterbyreference(orusingArray10=for_each(Array,&Array10,for_each(Array,Array+10,n)std:cout nVC+ 的博客,如下使用 STL 为什么? CalculateSum(10,20,为什么? CalculateSum(10,20,n)std:coutsumis:n;/C2664:CalculateSum:cannotconvertparameter3 voidstd:coutSumis:returnautoGetPI()-returnIt returns a long, asyou can see.
28、It uses the newsyntaxof specifying a return type, the actual type is specified after the -operator. One more exautoGetCPUSpeedInHertz()-return同理,其他的STL 函数,如,等等,可以工作在三种情况下:函数指针,函数对象,API函数中使用 表达式,如SetTimerEnumFontFami s,等等别再计划了!即使强制类型转换 表达式(通过传递它的地址),也不会工作,程序会在运行时 。TrailingreturnLets start wisimpleexl
29、e.Followingisafunctionwhosereturntypeislong. This is not a lambda, but a function.templatedecltype(t1+returnt1+AddThem(10.0,AddThem(C+, X); template SecondType AddThem(Type t1, SecondType t2);templateType,typename/*UnknonwnReturnType*/ Typet1,SecondTypereturnt1+decltypekeywordabove,torecollect.Forbo
30、thofthefunctionsgivenabove,you obviously need not use this feature!Wheretoactuallyuse Considerthetemplatefunctionwithsomeypes.t,thecompilerwontbotherKindlyignorefunctionwithsomeypes.t,thecompilerwontbotherKindlyignorethemissingcopyconstructor,weareusingthedefaultconstructor.Forunderstanding,methecop
31、yconstructor(oravoidSetSimple(constSimple&/CreateaSimpleobjectfromSimpleobject/UseHere,youcanttheGetSimplemethodreturnsaSimpleobject.SetSimpletakesaSimpleobjectbyreference.InacalltoSetSimple,weassoonasSetSimplereturns.LetsextendclassSimpleSimplereturnvoidSetSimple(const SetSimple(GetSimple()anything
32、(samerulesaswithnormaltemplateR-Value Ia me tyouknowwhatcall-by-value,byreference,andbyconstantreference mean.Ifurthera me tyouknowwh -valueand R-valuemean. Now,lets take an ex le where R-value referen would make sense:overloaded+operatorwouldbethereturntype.Iftypesarenotnative,andoverloadcouldbefou
33、nd,thecompilerwouldraiseanerror.Itisimportanttotthetypedeductionwillonlytakeplacewhenyouinstantiatethe sup edtodestroy100bytes.Dont sup edtodestroy100bytes.Dontgettheprobleminhere?Okay,letmeexplain. Twoobjectsarebeingcreated(oneinGetSimple,oneinSetSimple),andboth are allocating 100 bytes of memory.
34、Right? This is like copying a file/folder to anotherlocation.Butasyoucanseefromtheex lecode,onlyobjectis bytes allocated by rsof therewasnosimpleway,unlesswewroteourownmemory/objectroutines(liketheCStringclassdoes).InC+0 x,wecant. inshort,welloptimizetheroutinethistheproblemandsolutionisheformofRVOa
35、ndNRVO(Named meaningful.Forthis,weuseanewroduced:R-valueTheabovecodeisformovingthecontentfromtheoldobjecttothenewThisisverysimilartomovingafile/folder.NotetthesbeenvoidSetSimple(Simple&rSimple)/R-ValueNON-CONST/Performingmemoryassignmenthere,forSimpleobject.Memory=rSimple.Memory; rSimple.Memory = nu
36、llptr;/UsedeleteDeclarator:&.Basicsyntax:Type&identifier.NowwemodifytheabovestepbyBythis,wesave100bytes!Notabigamount,though.Butifthisfeatureisused objectiscreated,anditallocatesItisabouttobeBefore it gets destroyed, we attach the memory of theobjecttothe second object.Wedetachthememoryfromobject(li
37、ke,settingtheerWeusethesecondThesecondobjectgetsdestroyed,whicheventuallyde-allocatesthe memory originally allocated by the has a memory-poer(say,void*)namedMemory has a memory-poer(say,void*)namedMemory.Thedefaultconstructorsetsit as null. This member is made public for simplifying the topic.Whatif
38、youmakeacalllikeItwouldresultinanerrorsincethecompilercannotconvertSimpletoSimple&. Thevariablexisnottemporary,andcannotbehavelikeanR-valuereference.For this, we may provide an overloaded SetSimplefunction t takes Simple, Simple&, or constSimple&. Thus, you know by nowttemporaryobjectsare actually R
39、-value referen. With R-values, you achieve what is known as move moves,weneedtoprovideamoveconstructor,andoptionallyaThemove-constructorwouldbeverysimilar-justone Simple(constassignmentoperator(operator=),totheThemove Lets implement moving the object withheclassitselfwiththehelpofamove constructor.
40、As you know, a copy constructor would have a signature like:s.MovesenablesyoutowritecodettransfersSimple x; classvoid*Simple()Memory=nullptr;nBytes)Memory=newcharnBytes;SimpleSimplereturnsincewealsoneedtoreset(detach)thememoryoriginallyallocatedby But asyoucan see,themove-constructorisnon-const. Lik
41、e acopy constructorBut asyoucan see,themove-constructorisnon-const. Like acopy constructor takeconst;nothingpreventsthis-ngsoforfeitsthewholee wheretheso-calledmove-constructormaybeNow,methemove-constructorishatcase,thecompiler HereistheupdatedSimpleclassclass/Thevoid*Simple()Memory=nullptr;/TheMOVE
42、-Simple(Simple&/TakeMemory=/Unlikethecopy-constructor,thecompilerdoesnotprovideamove-constructor;youmustwriteittheobjectisbeingmoved(ownershiptransfer),anditwouldcall Why?TheobjectsObjhasbeencreatedonthestack.Thereturntypeiswhichwouldmeanthecopy-constructor(ifprovided;otherwise,therovided)would beca
43、lled. Further,thedestructor for sObjwould beSimplereturn sObj;writing a move-constructor. Why?If you understoodcorrectly, we are detachingresourceownershipfromtheoriginalsource(theargumentofHereisppenswhenyoucalltheGetSimpleHereisppenswhenyoucalltheGetSimpleItisimportanttonote,andunderstandcalled(de
44、faultoruser-Returning an object by value (i.e., Simple, not Simple&or Simple*) causes the copy-constructor or move-constructor to be called. This povery important to understand!Move-constructor detaches the object knowing what the destructor is his case, we are setting Memoryto null, sotDTOR doesnt
45、delete it.1. TheprogramcontrolenterstheGetSimplefunction,allocatesaSimpleobjectonCallsthe(creation)constructorofclassTheconstructorallocatesthedesirednumberofbytes(theThe return sementisreadytoconvertthestackobject sObjtoa returnable object.Here, the smart compiler findst the object iuallybeingmoved
46、;and t the move-constructor is available, it calls the MC.The move constructor (Simple(Simple&) now takes the Memorycontent (insteadofallocatingagain,asthecopy-constructorwouldhavedone).Then itsetstheoriginalobjectsMemorytobenull.Itdoesnotallocateandcopy the memory!Control comes back to return-po.No
47、wtheoriginalsObjistobe -doessObj.Memory=Memory=newif(Memory!=nullptr) delete Memory;Wetwemovedtheoriginalo thenewobject.Thisway,wememoryandsingWetwemovedtheoriginalo thenewobject.Thisway,wememoryandsingtime.Asmentionedr,thissavingisnegligent -Thesignatureoftheuser-definedoperatorcanWhatabouttheement
48、:obj3=GetSimple()?TheobjectreturnedGetSimpleistemporary, asyou should clearly knowby now.Thus, wecan(and classAndhereisthemodifiedSimpleclass(previouscodeomittedforbrevity).assignmentisnottakencarevoidoperator=(Simple&);/Modifiesthesource,sinceitis/voidreturnisputforvoidoperator=(constSimple&);/Does
49、ntmodifyThecompilerdoesnotprovidethedefaultmoveassignment-unlikethedefault(copy)assignmentAsyouknow,obj2=obj1wouldcalltheassignment-operator,thereisdontprovideanassignmentoperator,thecompilerwouldprovidetheassignmentoperator(andwouldcopybyte-by-byte).TheobjectontherightremainsSimple obj1(40); Simple
50、obj2,obj3;obj2=obj3=whenitisemployedinlargerdatastructures,and/orwhentemporary-objectscreatedanddestroyedalot,thesavingisThemoveassignment-Checkingifapo erisnull(Memory!=nullptr)isnotrequiredasperC+ standards,butismentionedforclarity.Onyourclasses,youmustdesignMC and DTORso t they have a similar pro
51、tocol.hecaseoftheobj3=GetSimple()ement,thehecaseoftheobj3=GetSimple()ement,thefollowingthingsTheGetSimplefunctionisbeingcalled,whichreturnsatemporaryNow, the spelfunction,moveassignment-operator,istobecalled.Since the compiler identifiest the argument to this spel-function is temporary, it calls the
52、 assignment-operator which takes the R-value reference. This case is the same as the SetSimplementioned above.Themove-assignment-operatortakestheownership,anddetachesthe ownership from the so-called temporary object/R-value reference.The destructor of the temporary-object gets called, which identifi
53、estthe object doesnt own any resource - it does nothing.voidoperator=(constSimple&/De-allocatedelete/Allocaterequiredamountof/andcopy/Thenewandmemcpycallsnot/forbrevity.Another/classisalsorequiredtoholdvoidoperator=(Simple&/De-allocatedelete/TakeothersmemoryMemory=/Sincewehavetakenthetemporarys/Deta
54、chsOther.Memory=Youcansimplysay,Providetheplus(+)heclass. anoperator+Youcansimplysay,Providetheplus(+)heclass. anoperator+inourSimple(fortheobj3=obj1+obj2),andtheresourceis-enough!(Ihopeyouunderstanditfully beforeyoumoveto thenext paragraph.) the next sement(obj2=GetSimple()+obj1),theobject on the l
55、eft itself is temporary. Notet in SetSimple andhe move spel-functions, theargumentistemporary,his.Thereisnotechniquey class/GivestohelperfriendSimpleoperator+(Simple&left,constSimple&tomakethisatemporaryobject.Okay,okay,IamnotBjarneStroustrup;heretheNow,asyoucansee,atemporaryobjectiscreatedandisbein
56、greturned/ThismethodisINSIDEtheSimpleoperator+(constSimple/Dobinary+operationreturnSimpleobj1(10),obj2(20),obj3,obj4;/Pardonmeforusingsuchobj3=obj1 +obj2=GetSimple()+obj1; obj4=obj2+obj1+ (inshort,allthree)mustagreewiththesameprotocolforAnotherleme the Simple class we have been working on is some do
57、ntainer; like string, date/time, array, or anything you prefer.t dontaineriallow the following, with the help of operator overloading:Externalobj4 =obj2+obj1 +obj4=t1 +Externalobj4 =obj2+obj1 +obj4=t1 +obj4 =Hereitgoesinamoresimplified,non-verbalform(italicisthecallbeing, the normal class verofoperator+iscalled(forobj2+obj1).It returns a new Simpleobject, we call it t1.Now with t1 (theeofobj2+obj1),whichisatemporaryobject, operator+ gets called again (t1+obj3) - the out-of-class veroperator+is called, which takes ownership from t1.Theglobaloperato
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论