




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
第六章類成員(一)面向?qū)ο蟪绦蛟O(shè)計(jì)(C++)6類成員(一)6.1成員變量與成員函數(shù)6.2this指針6.3成員對(duì)象6.4const(常量)6.5const對(duì)象與const成員函數(shù)6.6靜態(tài)成員變量與靜態(tài)成員函數(shù)6.1成員變量與成員函數(shù)6.1.1成員變量可以是基本類型、構(gòu)造類型,甚至是一個(gè)另一個(gè)類的對(duì)象、對(duì)象指針或引用;
classX{private:
int
basetypemem;//基本類型
charstr[20];//構(gòu)造類型
Cstack
obj_stack;//另一個(gè)類的對(duì)象,stack必須
//在X之前定義
CTime*obj_time;//另一個(gè)類的對(duì)象指針
CTime&obj_time;//另一個(gè)類的對(duì)象引用
…;}6.1.1成員變量(續(xù))提前聲明:一個(gè)類提前聲明之后,這個(gè)類的對(duì)象指針、引用可以作為另一個(gè)類的成員變量。但這個(gè)類的對(duì)象不能作另一個(gè)類的成員變量。
classStack;classStackofStack{
int
topStack; Stack*stackstorage;};
6.1.2成員函數(shù)在類的定義體外定義:classStack{
intempty();voidpop();
inttop(); voidpush(int);};
intStack::empty(){return(nb_elements==0);}6.1.2成員函數(shù)(續(xù))在定義體內(nèi)定義
classStack{
intempty(){return(nb_elements==0);} voidpop();
inttop(); voidpush(int);};
在類的定義體內(nèi)定義時(shí),自動(dòng)成為內(nèi)聯(lián)函數(shù)。6.1.3對(duì)象與類創(chuàng)建對(duì)象類對(duì)象1,對(duì)象2,對(duì)象n;
Stackintstack(10),stringstack;存儲(chǔ)分配
一個(gè)類所有的對(duì)象的成員變量(除了靜態(tài)變量)都有獨(dú)立空間,但同一個(gè)類的所有對(duì)象成員共享同一組成員函數(shù)。6.2this指針6.2this指針問題:當(dāng)類的多個(gè)實(shí)例同時(shí)存在時(shí),在一個(gè)類的成員函數(shù)內(nèi)部引用一個(gè)數(shù)據(jù)成員,并沒有指明一個(gè)類的具體實(shí)例。編譯器如何決定引用哪個(gè)對(duì)象的數(shù)據(jù)成員呢?
Eg:classCTest{private:
intn;public:
int
getn(){returnn;}}對(duì)哪個(gè)對(duì)象的n進(jìn)行操作呢?nnnngetn()6.2.1隱藏的this指針解決辦法:編譯器給成員函數(shù)傳遞一個(gè)隱藏的對(duì)象指針參數(shù),該指針總是指向當(dāng)前要引用的對(duì)象。稱為“this指針”實(shí)現(xiàn)方法:類X中的每個(gè)成員函數(shù)都隱式地聲明this指針;
int
CTest::getn(X*constthis){returnthis->n;//等價(jià)于returnn;}
classCTest{private:
intn;public:
int
getn();}
int
CTest::getn(X*constthis){returnthis->n;//等價(jià)于returnn;}nnn返回this指向的對(duì)象的ngetn()n操作的是this->n!例1:classTest{public:Test(int=0);//defaultconstructorvoidprint()const;private:
intx;};Test::Test(inta){x=a;}//constructorvoidTest::print()const{
cout<<"x="<<x<<"\nthis->x="<<this->x<<"\n(*this).x="<<(*this).x<<endl;}例1:voidmain(){TesttestObject(12);
testObject.print();}運(yùn)行結(jié)果:x=12this->x=12(*this).x=126.2.2this是一個(gè)常量指針X*constthis:不能修改this指針的值;
int
Ctest::setn(){Ctestt1;
this=newt1;//非法操作,不能改變this指針
}
6.2.3this指針的用途之一通過返回*this的引用,可以實(shí)現(xiàn)成員函數(shù)的鏈?zhǔn)秸{(diào)用
ClassX{X&assign(){…;return(*this)};X&setvalue(){…;return(*this)};…;
}XobjX;
objX.assign().setvalue().assign();(.
從左向右結(jié)合)
//Fig.7.8:time6.hclassTime{public:Time(int=0,int=0,int=0);//defaultconstructorTime&setTime(int,int,int);//sethour,minute,second
Time&setHour(int);//sethour
Time&setMinute(int);//setminuteTime&setSecond(int);//setsecond
int
getHour()const;//returnhour
int
getMinute()const;//returnminute
int
getSecond()const;//returnsecondvoidprintMilitary()const;//printmilitarytimevoidprintStandard()const;//printstandardtimeprivate:
inthour;//0-23
intminute;//0-59
intsecond;//0-59};//Fig.7.8:time.cpp
#include"time6.h"#include<iostream.h>Time::Time(inthr,intmin,intsec){setTime(hr,min,sec);}Time&Time::setTime(inth,intm,ints){setHour(h);
setMinute(m);
setSecond(s);return*this;//enablescascading}Time&Time::setHour(inth){hour=(h>=0&&h<24)?h:0;
return*this;//enablescascading}Time&Time::setMinute(intm){minute=(m>=0&&m<60)?m:0;
return*this;//enablescascading}Time&Time::setSecond(ints){second=(s>=0&&s<60)?s:0;
return*this;//enablescascading}int
Time::getHour()const{returnhour;}int
Time::getMinute()const{returnminute;}int
Time::getSecond()const{returnsecond;}voidTime::printMilitary()const{cout<<(hour<10?"0":"")<<hour<<":"<<(minute<10?"0":"")<<minute;}voidTime::printStandard()const{
cout<<((hour==0||hour==12)?12:hour%12)<<":"<<(minute<10?"0":"")<<minute<<":"<<(second<10?"0":"")<<second<<(hour<12?"AM":"PM");}//Fig.7.8:fig07_08.cpp#include<iostream.h>#include"time6.h"intmain(){Timet;
t.setHour(18).setMinute(30).setSecond(22);
cout<<"Militarytime:";
t.printMilitary();
cout<<"\nStandardtime:";
t.printStandard();
cout<<"\n\nNewstandardtime:";
t.setTime(20,20,20).printStandard();
cout<<endl;return0;}運(yùn)行結(jié)果:Militarytime:18:30Standardtime:6:30:22PMNewstandardtime:8:20:20PM思考:假如按值返回*this,問程序的輸出是什么?解答:
Militarytime:18:00Standardtime:6:00:00PMNewstandardtime:8:20:20PM6.2.4this指針的重要用途之二(略)防止自身賦值:
classString{private:char*str;public:String&assign(constString&s){
int
tmplen;
if(this==&s){error(“自身賦值”);return(*this);}else{
tmplen=strlen(s.str);delete(str)
str=newchar[tmplen+1];
strcpy(str,s.str);}}…;//};
Strings1(“Howareyou?”),s2(“Fine”);s1.assign(s2);s2.assign(s2);6.3成員對(duì)象6.3.1成員對(duì)象(對(duì)象成員)類的數(shù)據(jù)成員可以是另一個(gè)類的對(duì)象,這種數(shù)據(jù)成員稱為“成員對(duì)象”。classEmployee{private:charfirstName[25];charlastName[25];constDatebirthDate;constDatehireDate;…;//以下省略};6.3.2初始化次序構(gòu)造函數(shù)的執(zhí)行次序:對(duì)象成員的構(gòu)造函數(shù)先初始化,然后才是包含它的類的構(gòu)造函數(shù)。有多個(gè)對(duì)象成員時(shí),按照在類的定義中聲明的次序初始化。Employee:
先執(zhí)行:
birthDate.Date(…)
hireDate.Date(…)
再執(zhí)行:
e.Employee(…)birthDatehireDatefirstName[25]lastName[25]6.3.3成員初始化表如何初始化?成員初始化表:類的構(gòu)造函數(shù)名(類構(gòu)造函數(shù)參數(shù)列表+成員構(gòu)造函數(shù)參數(shù)列表):成員對(duì)象1(參數(shù)列表),成員對(duì)象2(參數(shù)列表)Employee::Employee(char*fname,char*lname,
int
bmonth,int
bday,int
byear,
int
hmonth,int
hday,int
hyear):birthDate(bmonth,bday,byear),
hireDate(hmonth,hday,hyear)例:成員對(duì)象(對(duì)象成員)的初始化#include"date1.h“classEmployee{public:Employee(char*,char*,int,int,int,int,int,int);voidprint()const;~Employee();//providedtoconfirmdestructionorderprivate:charfirstName[25];charlastName[25];constDatebirthDate;constDatehireDate;};Employee::Employee(char*fname,char*lname,
int
bmonth,int
bday,int
byear,
int
hmonth,int
hday,int
hyear):birthDate(bmonth,bday,byear),
hireDate(hmonth,hday,hyear){…;//構(gòu)造函數(shù)體;}voidEmployee::print()const{…;//略}//Destructor:providedtoconfirmdestructionorderEmployee::~Employee()構(gòu)造函數(shù)的參數(shù)表成員對(duì)象初始化表{
cout<<"Employeeobjectdestructor:"<<lastName<<","<<firstName<<endl;}#include<iostream.h>#include"emply1.h"intmain(){
Employeee("Bob","Jones",7,24,1949,3,12,1988);return0;}輸出:Dateobjectconstructorfordate7/24/1949Dateobjectconstructorfordate3/12/1988EmployeeobjectconstructorBobJones….EmployeeobjectdestructorBobJonesDateobjectdestructorfordate3/12/1988Dateobjectdestructorfordate
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 公司商務(wù)用車維修合同范本
- 2025年制動(dòng)分泵項(xiàng)目合作計(jì)劃書
- 2025年麻將涼席合作協(xié)議書
- 個(gè)體建材購銷合同范本
- 單位食堂供應(yīng)合同范例
- 2025年加氣加注設(shè)備項(xiàng)目建議書
- 家政公司家政公司加盟合同范本
- 2025年霍爾汽車點(diǎn)火系統(tǒng)合作協(xié)議書
- 農(nóng)村承包荒地合同范例
- 合同范本面布局
- 2025年湖南鐵道職業(yè)技術(shù)學(xué)院單招職業(yè)技能測試題庫附答案
- 個(gè)人車輛租賃給公司合同5篇
- 2025年上半年中國海油秋季校園招聘易考易錯(cuò)模擬試題(共500題)試卷后附參考答案
- 云南省勞動(dòng)合同范本
- 北京市石景山區(qū)2024-2025學(xué)年高三上學(xué)期期末英語試題【含答案解析】
- 2024-2025年中國鋰電池隔膜行業(yè)未來發(fā)展趨勢分析及投資規(guī)劃建議研究報(bào)告
- 2024年南昌健康職業(yè)技術(shù)學(xué)院高職單招職業(yè)技能測驗(yàn)歷年參考題庫(頻考版)含答案解析
- 2025浙江中煙招聘高頻重點(diǎn)提升(共500題)附帶答案詳解
- 月子會(huì)所護(hù)理人員禮儀
- 校園安全隱患排查培訓(xùn)
- 《化妝品包裝材料相容性試驗(yàn)評(píng)估指南》
評(píng)論
0/150
提交評(píng)論