细部检视类别.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
第三章 細部檢視類別 3-1 指定物件 3-2 傳遞物件給函數 3-3 從函數中傳回物件 3-4 簡介夥伴函數 3-1 指定物件 物件之間的指定(assignment)運算 int x = 5, y ; y = x ; myclass ob1, ob2 ; ob1 = ob2 ; // what happen? What happen? struct test { int a , b ;} ; void main() { test t1, t2 ; t1.a = 10; t1.b = 20 ; t2 = t1 ; cout t2.a “ “ t2.b endl ; } 物件間的指定(assignment) #include iostream using namespace std ; class myclass { int a, b ; public: myclass(){} myclass(int x, int y) {a = x; b = y ;} void show() { cout a b ;} } ; void main() { myclass ob1(5, 3), ob2; ob2 = ob1 ;ob2.show() ; } 範例一: 指定敘述是否需同一類型? class myclass {int a, b ; public: void show();}; void myclass::show(){coutabendl;} class yourclass{ int a, b; public: void show();} ; void yourclass ::show(){coutabendl;} int main() { myclass ob1 ; yourclass ob2; ob1 = ob2 ; return 0 ; } 範例二: 物件中有複合資料 class stack { int stk[10] ; int tos; public: stack(){ tos=0; for(int i=0;i10;i++) stk[i]=0; } void push(int num) { stk[tos]=num; tos++; } 範例二: 物件中有複合資料 int main() { stack s1, s2 ; s1.push(10); s1.push(20); s1.print() ; s2 = s1 ; s2.print() ; return 0 ; } 範例三: 如果物件中有指標 class strtype { char *p ; int len ; public: strtype(){ p=new char[10]; len=1; p[0]=\0; } strtype(char *s) { p = new char[strlen(s)+1]; len=strlen(s)+1; p=strcpy(p, s) ; } ~strtype() { delete[] p ; } void setChar(int pos, char c) { p[pos] = c ; } void show(){ coutlenendl;} } ; void main() { strtype s1(“Hello”), s2 ; s2 = s1 ; s2.setChar(1, ‘x’) ; s1.show() ; } 範例三: Problem 1 範例三: Problem 2 void main() { strtype s1(“Hello”); strtype s2 ; s2 = s1 ; } 解決方式 void main() { strtype s1(“Hello”) ; strtype s2 ; s2 = s1 ; } void main() { strtype s1(“Hello”) ; strtype s2 ; s2.set(s1); } 解決方式 請寫operator= class strtype{ …… strtype operator=(const strtype s) { p = new char[s.len+1] ; strcpy(p, s.p) ; len = s.len ; return *this ; } } ; 解決方式 class strtype { char *p ; int len ; public: strtype(){ p=new char[1

文档评论(0)

xiaozu + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档